diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..97f6650ef3560375513fb87b8d5db55a816298eb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,18 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +code/tt_depthpro2/samples/kropa_street/image.jpg filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/1431ca2d06bf0e3d6b058e48861af84ab9e0a76124a34cfc8668fbc33128cf31 filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/26978a700289f033dd9238f908fb9bde859d9bf209a916db1a441ef7f08bbbcd filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/5b016d79bb0d0f231feb56432bca597d22372330cae9fcbd57b66a767a0e0bde filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/671912666b1102907184fdf4478ef31010aaa5d3e790c872ed63a6f305af1674 filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/8ea3df7e57eca539aaef3886da4416edc8049442de5819442ff93435714efda2 filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/a0f9120f8473031e9c31209f61fc7dd3ab859a2dfb3001d7dfd8b5996df48b72 filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/a90d913a3b293654e45a902690e86ee0a9cbee6dac59ccc9b8f5b6dcf70acfa0 filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/b2c200cde9649039e625dcd0b97cb038730866e1eea1f36fa1ade18f52890b37 filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/b5d78d46efec8b21102fcabc61b536b7c710fa075c56cc5573c7f25d000b2958 filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/ba082564e6605eeb2e1abc91a762985d2e8afea393433de08e798c1eee36d028 filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/bd2a1526ee7e957e7890edc94a56b8d87c4106f128c96d3dfc5dbe5c6ca324d4 filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/d43baab0c30010379faae769137459154234a3db3176feafda3ba268ba069d0f filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/e5758dccd78c32a99fa2ad6fede7dcdc9a010195d5b2e52fdf578ad053a5efe1 filter=lfs diff=lfs merge=lfs -text +image/blobs/sha256/fed26da465205879ddefd477dede4d90fccc48b762849d028c45f589ea4bf6f4 filter=lfs diff=lfs merge=lfs -text diff --git a/PYTHON.md b/PYTHON.md new file mode 100644 index 0000000000000000000000000000000000000000..cad91a5ee810aa54198dc3b8431e9631b82b6e0b --- /dev/null +++ b/PYTHON.md @@ -0,0 +1,134 @@ +# DepthPro2: Python API + +Apple's Depth Pro 2 (sizes S, B, L and H+) on one Tenstorrent Blackhole p150: monocular metric depth for images, +clips and videos. The HTTP server of this package (`tt_depthpro2.server.app`) serves exactly this API: a response +equals `model.infer(...).to_dict()` for the same image. + +The weights are Apple's and are not part of this package: they are downloaded from `apple/DepthPro2-*` at pinned +commits, under the **Apple Machine Learning Research Model License Agreement (research purposes only)**. Apple +Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement. See +[`tt_depthpro2/licenses/NOTICE.md`](tt_depthpro2/licenses/NOTICE.md). This package is a third-party port, not an +Apple product. + +## Install + +The container image has everything. Outside it you need a host build of tt-metal (`ttnn`) at the commit of the +package's Provenance with the patches in `patches/` applied, then, from the root of the model repo: + +```bash +pip install -e . # numpy<2, pillow, safetensors, huggingface_hub (ttnn and torch come from tt-metal) +pip install -e ".[server,test]" # + fastapi, uvicorn, pytest +``` + +## Quickstart + +```python +from tt_depthpro2 import DepthPro2, load_sample + +with DepthPro2.from_pretrained("L") as model: # pinned weights -> chip (ETH dispatch, 12x10) -> warm-up + out = model.infer(load_sample()) # the shipped 640 x 480 street photo + print(out.depth.shape, out.focallength_px, out.focal_source, out.timing_ms) + png, meta = out.png16() # 16-bit PNG, uint16 = round(depth_m * 1000), 0 = sky +``` + +## `DepthPro2.from_pretrained(size=None, *, resolutions=None, window=None, overlap=None, fov=None, engine=None, video_modes=None, clip_lengths=None, precision=None, device=None, device_id=None, dispatch=None, num_command_queues=None, weights_dir=None, fov_weights_dir=None, revision=None, fov_revision=None, backend=None, warmup=None)` + +Resolves the weights (before the chip is opened), opens the chip (unless `device` is given; `close()` then leaves +it open), builds the device programs for every resolution bucket and clip length, and runs one warm request per +bucket and clip length, so the first call is as fast as the next. Every setting is fixed for the model's lifetime; +`None` takes the `DEPTHPRO2_*` environment variable, else the default: + +| argument | env | default | meaning | +| --- | --- | --- | --- | +| `size` | `DEPTHPRO2_SIZE` | `L` | `S`, `B`, `L`, `H` (H+) or a serve-profile name `s` / `b` / `l` / `h` | +| `resolutions` | `DEPTHPRO2_RESOLUTIONS` | `vga,vga_portrait` | buckets: `HxW` sizes or presets (below), comma-separated or a list, at most 8 | +| `window` | `DEPTHPRO2_WINDOW` | 16 | video clip length T (buffered) / cache size (unbuffered), 1..16 | +| `overlap` | `DEPTHPRO2_OVERLAP` | 4 (at most window - 1) | frames shared by consecutive buffered clips | +| `clip_lengths` | `DEPTHPRO2_CLIP_LENGTHS` | `auto` (1 and the window) | clip lengths to serve: `all` (1..window) or a list; with the ttnn encoder every length up to the window runs on the window's program anyway (a runtime valid-frame count), an engine without one compiles each listed length | +| `video_modes` | `DEPTHPRO2_VIDEO_MODES` | `auto` | `buffered`, `unbuffered`, both, or `auto` = both when the unbuffered key-value caches (every bucket x `kv_streams`) fit `config.KV_BUDGET_BYTES` (4 GB), else `buffered` | +| `kv_streams` | `DEPTHPRO2_KV_STREAMS` | 1 | unbuffered streams open at once (one cache per bucket each, allocated at start; more raise `CapacityError`) | +| `fov` | `DEPTHPRO2_FOV` | true | load the focal-length (FOV) estimator `apple/DepthPro2-focal` | +| `engine` | `DEPTHPRO2_ENGINE` | `enc=mk,dec=mk,fov=mk` | per stage `mk` (persistent megakernel) or `ttnn` (its tt-nn fallback), e.g. `"dec=ttnn"` (stages not named keep the default) or one kind for all | +| `precision` | `DEPTHPRO2_PRECISION` | the device module's default | `bf16`, or `bfp8` where the device module offers it | +| `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-/`, `DepthPro2-focal/`), used offline | +| `revision`, `fov_revision` | | the pins | other commits of the size / focal repo | +| `device_id`, `dispatch`, `num_command_queues` | `TT_DEVICE_ID`, `DEPTHPRO2_DISPATCH`, `DEPTHPRO2_NUM_CQS` | 0, `eth`, 1 | the chip; `dispatch="worker"` is an A/B opt-in (11x10 grid) | +| `backend` | `DEPTHPRO2_BACKEND` | `tt` | `cpu` runs the same host pipeline on the float32 CPU reference (no chip; slow; tests and reference outputs) | +| `warmup` | | true on the chip | run the warm requests | + +Resolution presets: `qvga` 240x320, `qvga_portrait` 320x240, `vga` 480x640, `vga_portrait` 640x480, `square` +512x512, `720p` 720x1280, `720p_portrait` 1280x720, `1080p` 1080x1920, `1080p_portrait` 1920x1080. A bucket is a +native input size; the device runs it padded to a multiple of 32 (replicate padding, as the official code: 720x1280 +runs as 736x1280). Each bucket and clip length is a separate device program and trace, so start-up time and device +memory grow with them. + +## Calls + +- `model.infer(image, f_px=None, *, use_exif=True) -> DepthOutput` -- one image: a path, file bytes, a PIL image, an + RGB uint8 `(H, W, 3)` array, a `(3, H, W)` tensor or a float array in [0, 1]. Files are turned upright per their + EXIF orientation. `model(image)` is the same call. +- `model.infer_clip(frames, f_px=None) -> DepthOutput` -- T frames of one size (a list of images or a uint8 + `(T, H, W, 3)` array) as ONE clip: the frames attend each other in the cross-frame blocks and share one focal + length. T must be a compiled clip length (`model.clip_lengths`). +- `model.infer_video(frames, window=None, overlap=None, f_px=None, *, mode="buffered") -> Iterator[DepthOutput]` -- + one output per frame, in order (`frame_index`), as the official `infer_video`: **buffered** predicts clips of + `window` frames overlapping by `overlap` and cross-fades the overlaps with a linear ramp; the focal length is the + median FOV estimate over the first window, used for every frame. `frames` is read lazily. **unbuffered**: each + frame attends a key-value cache of the `window - 1` frames before it and is returned at once (Apple's unbuffered + `DepthStream`); it holds one of the `kv_streams` caches while it runs. +- `model.stream(f_px=None, *, mode="buffered", window=None, overlap=None) -> VideoSession` -- a live stream: + `session.step(frame)` returns the frames it finishes (a buffered stream returns nothing until a window is full), + `session.flush()` the rest; the focal length is the median estimate over the frames predicted so far, fixed once a + window of estimates is in (the official `DepthStream`). + +Sizes: an input of exactly a bucket's size runs natively. Any other size is resized (bilinear, antialias) to the +bucket with the nearest aspect ratio (ties: the nearest area) and the outputs are resized back to the input size; +the focal-normalized inverse depth does not change under resizing, and the FOV focal length is converted to input +pixels. An input whose aspect ratio differs from every bucket is stretched to the nearest one, which changes the +geometry the network sees: configure a bucket of your camera's aspect ratio for the best results. + +Focal length (`focal_source`): the `f_px` argument (`"request"`), else the image's EXIF 35 mm-equivalent focal length +(`"exif"`, files only, `use_exif`), else the FOV estimator (`"fov"`); without any of them `depth` is None. + +Client mistakes (undecodable image, wrong sizes, an uncompiled clip length, a disabled video mode) raise +`tt_depthpro2.io.InputError` (a `ValueError`); an unbuffered stream beyond `kv_streams` raises +`tt_depthpro2.io.CapacityError` (an `InputError`; HTTP 429). + +## Output: `DepthOutput` + +| field | meaning | +| --- | --- | +| `inverse_depth` | float32 torch tensor `(H, W)` (`(T, H, W)` for a clip): the network's focal-normalized inverse depth | +| `depth` | metres along the optical axis, `f_px / (W * inverse_depth)`; `inf` where the inverse depth is 0 (sky); None without a focal length | +| `focallength_px`, `focal_source`, `fov_deg` | the focal length in input pixels, where it came from, the FoV estimate per frame `[hfov, vfov]` | +| `input_size`, `bucket`, `device_size`, `resized` | the input `(H, W)`, the bucket it ran at, the padded device size, whether it was resized | +| `frames`, `frame_index` | the clip length; the video frame index (video outputs) | +| `timing_ms` | `preprocess`, `device`, `fov`, `postprocess`, `total` | + +`out.to_dict(output_format="npy16", include_inverse_depth=False, png_scale=1000)` is the `/predict` response +(`npy16` float16 `.npy` base64, `npy32`, `png16`, `none`); `out.png16(scale)` gives the 16-bit PNG bytes; +`out.stats()` the depth statistics. + +## Other members + +`model.info` (size, weights and commits, device, engines, configuration, warm-up), `model.buckets`, +`model.clip_lengths`, `model.config`, `model.warmup()`, `model.close()` (idempotent; also at interpreter exit; +`with` closes it). Calls are serialised by a lock; one model per process per chip. + +## Tests + +```bash +# host (no device): config, streaming, the API on the CPU reference against Apple's float32 goldens, the HTTP server +PYTHONPATH=/research/packaging/scripts:code TT_VISIBLE_DEVICES=none \ + python -m pytest -p fake_ttnn_plugin code/tt_depthpro2/tests/test_host_*.py +# device (one p150): name the files +bin/devrun -t 3600 -- python -m pytest -q -s code/tt_depthpro2/tests/test_device_.py +``` + +## Limits + +Batch 1 (a clip is up to `window` frames); requests are serialised. One p150 (ETH dispatch: no multi-chip mesh). +The resolution buckets and the window are fixed when the model is built; a clip shorter than the window runs on the +window's program and costs as much. Inputs of other sizes are resized to a bucket (configure your camera's native +resolution for the most faithful results). Unbuffered video steps always run the tt-nn encoder (the megakernel +encoder has no key-value cache path). Research use only (Apple's licence). diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..da4f1d930842958171f3199be8b5be4794c2a788 --- /dev/null +++ b/README.md @@ -0,0 +1,314 @@ +--- +tags: +- blackhole +- p150 +- tt-dit-server +- tt-model-cache +- tt-model-container +license: other +license_name: apple-amlr +license_link: https://huggingface.co/apple/DepthPro2/blob/main/LICENSE +pipeline_tag: depth-estimation +base_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 + +```bash +tt 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: + +```bash +curl -sLO https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/samples/kropa_street/image.jpg +python3 -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.json +curl -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 and +returns a 16-bit depth PNG; `POST /predict_video` takes the frames of a clip or video and returns one depth map +per 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 chat +API. + +| 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` and +further `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": "", "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 variables +in the container's launch command (`tt-model serve --print` prints it) and start it again. `GET /config` reports +it. + +| 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's +program. 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) in +parentheses: + +| 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's +focal length. Apple's float32 output exists for every case except the 375 x 500 image at L and H+, which is +compared 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. The +focal-length estimator is shared by every size. [1] L's prediction for this image is nearly flat (its inverse +depth 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 1000 +trace 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 (every +size 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+, with +1 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 640 +with 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 requests +returned float32 depth and inverse depth for every frame, which is part of their time). A served request adds +image 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 start +compiles 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 | + diff --git a/SERVING.md b/SERVING.md new file mode 100644 index 0000000000000000000000000000000000000000..6f00564ce796f0018f21d68013250eead4d2e052 --- /dev/null +++ b/SERVING.md @@ -0,0 +1,106 @@ +# 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) + +```bash +source /bin/tt-env.sh # tt-metal python_env (ttnn, torch 2.11.0+cpu) + fastapi / uvicorn +cd /code +# optional: DEPTHPRO2_WEIGHTS_DIR=/ 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:app +python3 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 -- ...`). The server logs `Loading weights`, `Opening device`, `Warming up` per bucket and clip +length, `Warmup complete`, then uvicorn's `Application startup complete`. `DEPTHPRO2_BACKEND=cpu` serves the float32 +CPU reference instead of the device (slow; for testing the HTTP contract without a chip). + +## 2. Package, serve and smoke with tt-model + +```bash +cd # every tt-model command runs from here +sg docker -c "tt-model package --container tt-model.yaml --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 /depthpro2 20000 --profile l +tt-model push /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) whichever +profile 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-`), not a chat API | +| `POST /predict` | JSON `{"image": , "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": [...] | "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: : `. + +## 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 (for +example `DEPTHPRO2_RESOLUTIONS=720p,vga`) and run it; `GET /config` shows what runs. Every bucket and clip length is +a 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. diff --git a/build_info.json b/build_info.json new file mode 100644 index 0000000000000000000000000000000000000000..fad15fc5a5e31037bcddc863b9d36a1e2cd9545e --- /dev/null +++ b/build_info.json @@ -0,0 +1,46 @@ +{ + "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:); these are the digests this image was built from. A moved build base costs a cold C++ build." +} diff --git a/code/PYTHON.md b/code/PYTHON.md new file mode 100644 index 0000000000000000000000000000000000000000..cad91a5ee810aa54198dc3b8431e9631b82b6e0b --- /dev/null +++ b/code/PYTHON.md @@ -0,0 +1,134 @@ +# DepthPro2: Python API + +Apple's Depth Pro 2 (sizes S, B, L and H+) on one Tenstorrent Blackhole p150: monocular metric depth for images, +clips and videos. The HTTP server of this package (`tt_depthpro2.server.app`) serves exactly this API: a response +equals `model.infer(...).to_dict()` for the same image. + +The weights are Apple's and are not part of this package: they are downloaded from `apple/DepthPro2-*` at pinned +commits, under the **Apple Machine Learning Research Model License Agreement (research purposes only)**. Apple +Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement. See +[`tt_depthpro2/licenses/NOTICE.md`](tt_depthpro2/licenses/NOTICE.md). This package is a third-party port, not an +Apple product. + +## Install + +The container image has everything. Outside it you need a host build of tt-metal (`ttnn`) at the commit of the +package's Provenance with the patches in `patches/` applied, then, from the root of the model repo: + +```bash +pip install -e . # numpy<2, pillow, safetensors, huggingface_hub (ttnn and torch come from tt-metal) +pip install -e ".[server,test]" # + fastapi, uvicorn, pytest +``` + +## Quickstart + +```python +from tt_depthpro2 import DepthPro2, load_sample + +with DepthPro2.from_pretrained("L") as model: # pinned weights -> chip (ETH dispatch, 12x10) -> warm-up + out = model.infer(load_sample()) # the shipped 640 x 480 street photo + print(out.depth.shape, out.focallength_px, out.focal_source, out.timing_ms) + png, meta = out.png16() # 16-bit PNG, uint16 = round(depth_m * 1000), 0 = sky +``` + +## `DepthPro2.from_pretrained(size=None, *, resolutions=None, window=None, overlap=None, fov=None, engine=None, video_modes=None, clip_lengths=None, precision=None, device=None, device_id=None, dispatch=None, num_command_queues=None, weights_dir=None, fov_weights_dir=None, revision=None, fov_revision=None, backend=None, warmup=None)` + +Resolves the weights (before the chip is opened), opens the chip (unless `device` is given; `close()` then leaves +it open), builds the device programs for every resolution bucket and clip length, and runs one warm request per +bucket and clip length, so the first call is as fast as the next. Every setting is fixed for the model's lifetime; +`None` takes the `DEPTHPRO2_*` environment variable, else the default: + +| argument | env | default | meaning | +| --- | --- | --- | --- | +| `size` | `DEPTHPRO2_SIZE` | `L` | `S`, `B`, `L`, `H` (H+) or a serve-profile name `s` / `b` / `l` / `h` | +| `resolutions` | `DEPTHPRO2_RESOLUTIONS` | `vga,vga_portrait` | buckets: `HxW` sizes or presets (below), comma-separated or a list, at most 8 | +| `window` | `DEPTHPRO2_WINDOW` | 16 | video clip length T (buffered) / cache size (unbuffered), 1..16 | +| `overlap` | `DEPTHPRO2_OVERLAP` | 4 (at most window - 1) | frames shared by consecutive buffered clips | +| `clip_lengths` | `DEPTHPRO2_CLIP_LENGTHS` | `auto` (1 and the window) | clip lengths to serve: `all` (1..window) or a list; with the ttnn encoder every length up to the window runs on the window's program anyway (a runtime valid-frame count), an engine without one compiles each listed length | +| `video_modes` | `DEPTHPRO2_VIDEO_MODES` | `auto` | `buffered`, `unbuffered`, both, or `auto` = both when the unbuffered key-value caches (every bucket x `kv_streams`) fit `config.KV_BUDGET_BYTES` (4 GB), else `buffered` | +| `kv_streams` | `DEPTHPRO2_KV_STREAMS` | 1 | unbuffered streams open at once (one cache per bucket each, allocated at start; more raise `CapacityError`) | +| `fov` | `DEPTHPRO2_FOV` | true | load the focal-length (FOV) estimator `apple/DepthPro2-focal` | +| `engine` | `DEPTHPRO2_ENGINE` | `enc=mk,dec=mk,fov=mk` | per stage `mk` (persistent megakernel) or `ttnn` (its tt-nn fallback), e.g. `"dec=ttnn"` (stages not named keep the default) or one kind for all | +| `precision` | `DEPTHPRO2_PRECISION` | the device module's default | `bf16`, or `bfp8` where the device module offers it | +| `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-/`, `DepthPro2-focal/`), used offline | +| `revision`, `fov_revision` | | the pins | other commits of the size / focal repo | +| `device_id`, `dispatch`, `num_command_queues` | `TT_DEVICE_ID`, `DEPTHPRO2_DISPATCH`, `DEPTHPRO2_NUM_CQS` | 0, `eth`, 1 | the chip; `dispatch="worker"` is an A/B opt-in (11x10 grid) | +| `backend` | `DEPTHPRO2_BACKEND` | `tt` | `cpu` runs the same host pipeline on the float32 CPU reference (no chip; slow; tests and reference outputs) | +| `warmup` | | true on the chip | run the warm requests | + +Resolution presets: `qvga` 240x320, `qvga_portrait` 320x240, `vga` 480x640, `vga_portrait` 640x480, `square` +512x512, `720p` 720x1280, `720p_portrait` 1280x720, `1080p` 1080x1920, `1080p_portrait` 1920x1080. A bucket is a +native input size; the device runs it padded to a multiple of 32 (replicate padding, as the official code: 720x1280 +runs as 736x1280). Each bucket and clip length is a separate device program and trace, so start-up time and device +memory grow with them. + +## Calls + +- `model.infer(image, f_px=None, *, use_exif=True) -> DepthOutput` -- one image: a path, file bytes, a PIL image, an + RGB uint8 `(H, W, 3)` array, a `(3, H, W)` tensor or a float array in [0, 1]. Files are turned upright per their + EXIF orientation. `model(image)` is the same call. +- `model.infer_clip(frames, f_px=None) -> DepthOutput` -- T frames of one size (a list of images or a uint8 + `(T, H, W, 3)` array) as ONE clip: the frames attend each other in the cross-frame blocks and share one focal + length. T must be a compiled clip length (`model.clip_lengths`). +- `model.infer_video(frames, window=None, overlap=None, f_px=None, *, mode="buffered") -> Iterator[DepthOutput]` -- + one output per frame, in order (`frame_index`), as the official `infer_video`: **buffered** predicts clips of + `window` frames overlapping by `overlap` and cross-fades the overlaps with a linear ramp; the focal length is the + median FOV estimate over the first window, used for every frame. `frames` is read lazily. **unbuffered**: each + frame attends a key-value cache of the `window - 1` frames before it and is returned at once (Apple's unbuffered + `DepthStream`); it holds one of the `kv_streams` caches while it runs. +- `model.stream(f_px=None, *, mode="buffered", window=None, overlap=None) -> VideoSession` -- a live stream: + `session.step(frame)` returns the frames it finishes (a buffered stream returns nothing until a window is full), + `session.flush()` the rest; the focal length is the median estimate over the frames predicted so far, fixed once a + window of estimates is in (the official `DepthStream`). + +Sizes: an input of exactly a bucket's size runs natively. Any other size is resized (bilinear, antialias) to the +bucket with the nearest aspect ratio (ties: the nearest area) and the outputs are resized back to the input size; +the focal-normalized inverse depth does not change under resizing, and the FOV focal length is converted to input +pixels. An input whose aspect ratio differs from every bucket is stretched to the nearest one, which changes the +geometry the network sees: configure a bucket of your camera's aspect ratio for the best results. + +Focal length (`focal_source`): the `f_px` argument (`"request"`), else the image's EXIF 35 mm-equivalent focal length +(`"exif"`, files only, `use_exif`), else the FOV estimator (`"fov"`); without any of them `depth` is None. + +Client mistakes (undecodable image, wrong sizes, an uncompiled clip length, a disabled video mode) raise +`tt_depthpro2.io.InputError` (a `ValueError`); an unbuffered stream beyond `kv_streams` raises +`tt_depthpro2.io.CapacityError` (an `InputError`; HTTP 429). + +## Output: `DepthOutput` + +| field | meaning | +| --- | --- | +| `inverse_depth` | float32 torch tensor `(H, W)` (`(T, H, W)` for a clip): the network's focal-normalized inverse depth | +| `depth` | metres along the optical axis, `f_px / (W * inverse_depth)`; `inf` where the inverse depth is 0 (sky); None without a focal length | +| `focallength_px`, `focal_source`, `fov_deg` | the focal length in input pixels, where it came from, the FoV estimate per frame `[hfov, vfov]` | +| `input_size`, `bucket`, `device_size`, `resized` | the input `(H, W)`, the bucket it ran at, the padded device size, whether it was resized | +| `frames`, `frame_index` | the clip length; the video frame index (video outputs) | +| `timing_ms` | `preprocess`, `device`, `fov`, `postprocess`, `total` | + +`out.to_dict(output_format="npy16", include_inverse_depth=False, png_scale=1000)` is the `/predict` response +(`npy16` float16 `.npy` base64, `npy32`, `png16`, `none`); `out.png16(scale)` gives the 16-bit PNG bytes; +`out.stats()` the depth statistics. + +## Other members + +`model.info` (size, weights and commits, device, engines, configuration, warm-up), `model.buckets`, +`model.clip_lengths`, `model.config`, `model.warmup()`, `model.close()` (idempotent; also at interpreter exit; +`with` closes it). Calls are serialised by a lock; one model per process per chip. + +## Tests + +```bash +# host (no device): config, streaming, the API on the CPU reference against Apple's float32 goldens, the HTTP server +PYTHONPATH=/research/packaging/scripts:code TT_VISIBLE_DEVICES=none \ + python -m pytest -p fake_ttnn_plugin code/tt_depthpro2/tests/test_host_*.py +# device (one p150): name the files +bin/devrun -t 3600 -- python -m pytest -q -s code/tt_depthpro2/tests/test_device_.py +``` + +## Limits + +Batch 1 (a clip is up to `window` frames); requests are serialised. One p150 (ETH dispatch: no multi-chip mesh). +The resolution buckets and the window are fixed when the model is built; a clip shorter than the window runs on the +window's program and costs as much. Inputs of other sizes are resized to a bucket (configure your camera's native +resolution for the most faithful results). Unbuffered video steps always run the tt-nn encoder (the megakernel +encoder has no key-value cache path). Research use only (Apple's licence). diff --git a/code/conftest.py b/code/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fa0c93b038aea86634c1d6c0b94f8a6da805c1b4 --- /dev/null +++ b/code/conftest.py @@ -0,0 +1,62 @@ +# 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_.py``. +- Host tests (``tests/test_host_*.py``) never open a device; run them on the fake ttnn: + ``PYTHONPATH=/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 gc +import importlib.util +import 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) diff --git a/code/models/common/lightweightmodule.py b/code/models/common/lightweightmodule.py new file mode 100644 index 0000000000000000000000000000000000000000..6743db9026f0547737bda649db0b3ab8c78289c0 --- /dev/null +++ b/code/models/common/lightweightmodule.py @@ -0,0 +1,12 @@ +# 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) diff --git a/code/scripts/bench.py b/code/scripts/bench.py new file mode 100644 index 0000000000000000000000000000000000000000..8b4a50d9e9c15690a8f72326e2b39d27f7883c0b --- /dev/null +++ b/code/scripts/bench.py @@ -0,0 +1,153 @@ +#!/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 argparse +import json +import os +import statistics +import sys +import time +from pathlib import Path +from 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()) diff --git a/code/scripts/bench_baseline.py b/code/scripts/bench_baseline.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb341e05637c0dc74c8d3b8ad2b31cc5946fe75 --- /dev/null +++ b/code/scripts/bench_baseline.py @@ -0,0 +1,300 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Benchmark of the ttnn baseline engines: traced device time per stage (ENC, DEC, FOV) per size / bucket / T, DRAM +and 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 only +enqueueing ``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 (allocation +failure) is recorded as ``fits: false`` and the run continues. +""" + +from __future__ import annotations + +import argparse +import gc +import json +import os +import sys +import time +import 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: E402 +from tt_depthpro2.reference import model as ref # noqa: E402 +from tt_depthpro2.tt import StageShape # noqa: E402 +from tt_depthpro2.tt import ttnn_dec, ttnn_enc, ttnn_fov # noqa: E402 +from tt_depthpro2.tt.model import DepthPro2Device # noqa: E402 +from 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() diff --git a/code/scripts/container_smoke.sh b/code/scripts/container_smoke.sh new file mode 100644 index 0000000000000000000000000000000000000000..348ad94a3c7b94402c27db3f447d7f438538a40e --- /dev/null +++ b/code/scripts/container_smoke.sh @@ -0,0 +1,138 @@ +#!/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 +# /tt_kernel_manifest.json` lists them; without --profile the package's default profile is served): +# +# bash code/scripts/container_smoke.sh [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. +# /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 +# [-]-.*: +# .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 -u +usage() { echo "usage: container_smoke.sh [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 ;; + esac +done +[ ${#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-- (tt_kernel/container.py). +read -r NAME PROFILE_NAME < <(python3 - "$MANIFEST" "$PROFILE" <<'EOF' +import json, sys +m = 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}" +fi +LOG_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.request +try: + 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=0 +cleanup() { + 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, sys +out, 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 EXIT +trap 'exit 143' TERM +trap '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 1 +step 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" diff --git a/code/scripts/device_server_smoke.py b/code/scripts/device_server_smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..9fcf104588faf5f223c1c3480027b0b445cb3df2 --- /dev/null +++ b/code/scripts/device_server_smoke.py @@ -0,0 +1,492 @@ +#!/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 the +device 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 --out-dir + # 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 --out-dir \\ + [--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..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___.json`` (all metrics and timings) to ``--out-dir`` and prints a summary. +""" +from __future__ import annotations + +import argparse +import base64 +import datetime as _dt +import io +import json +import os +import socket +import statistics +import sys +import threading +import time +from pathlib import Path +from 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.999 +UNBUF_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()) diff --git a/code/scripts/make_demo.py b/code/scripts/make_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..771594d1d53f4c79b07fa9b61542957a0bd8d352 --- /dev/null +++ b/code/scripts/make_demo.py @@ -0,0 +1,85 @@ +#!/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, sky +black), 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 argparse +import base64 +import io +import json +import sys +from pathlib import Path + +import numpy as np +from 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()) diff --git a/code/scripts/make_sample_reference.py b/code/scripts/make_sample_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..b6ef458414b650516f9fa6fcfd8523ebc8923f2e --- /dev/null +++ b/code/scripts/make_sample_reference.py @@ -0,0 +1,77 @@ +#!/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..json focal length, FoV, focal source, depth statistics, weights commits, how it was made + reference..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 container +with. 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 argparse +import datetime as _dt +import json +import os +import sys +import time +from 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-/ 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()) diff --git a/code/tt_depthpro2/__init__.py b/code/tt_depthpro2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ffa4200aa0607860f20607b10d7b7e77caa16423 --- /dev/null +++ b/code/tt_depthpro2/__init__.py @@ -0,0 +1,41 @@ +# 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, video +settings), ``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 smoke +test), ``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 Machine +Learning 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}") diff --git a/code/tt_depthpro2/api.py b/code/tt_depthpro2/api.py new file mode 100644 index 0000000000000000000000000000000000000000..0fa2af815165633cc2b02f6cce51dec2e489fd91 --- /dev/null +++ b/code/tt_depthpro2/api.py @@ -0,0 +1,907 @@ +# 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 request +and 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 the +table): the size (``S`` / ``B`` / ``L`` / ``H``, a serve profile ``s`` / ``b`` / ``l`` / ``h``), the resolution +buckets (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, the +per-stage engines (``mk`` / ``ttnn``) and the precision. Per call: the input, ``f_px``, and for video the frames +and the mode. + +Host pipeline per call (``reference/model.py`` functions): decode (EXIF-upright) -> ImageNet normalization -> the +bucket: native when the input is exactly a bucket's size, else a bilinear antialiased resize to the bucket of the +nearest aspect ratio -> replicate pad to a multiple of 32 -> device inverse depth -> crop -> resize back to the input +size (the focal-normalized inverse depth does not change under resizing) -> focal length (the caller's ``f_px``, the +image's EXIF 35 mm focal length, or the FOV estimator's median over the frames, at the bucket and scaled to the input +width) -> ``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 pipeline +on 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 atexit +import inspect +import logging +import math +import os +import threading +import time +import weakref +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple + +import numpy as np + +from . import config as C +from . import device as _device +from . 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().parent +SAMPLE_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//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-/`` 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 + + +@dataclass +class 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.register +def _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"" + + +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 = True diff --git a/code/tt_depthpro2/config.py b/code/tt_depthpro2/config.py new file mode 100644 index 0000000000000000000000000000000000000000..58f486b91f89a7303f1f0fcc702bd436f4a112c2 --- /dev/null +++ b/code/tt_depthpro2/config.py @@ -0,0 +1,394 @@ +# 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 explicit +arguments 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 other +size is resized (bilinear, antialias) to the bucket with the nearest aspect ratio and the outputs are resized back. +""" +from __future__ import annotations + +import math +import os +import re +from dataclasses import dataclass, field +from 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 -> size +PROFILES = {"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 derivatives +LICENSE_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 pixels +MAX_BUCKETS = 8 + +DEFAULT_WINDOW = 16 # the official DEFAULT_WINDOW +WINDOW_RANGE = (1, 16) +DEFAULT_OVERLAP = 4 # the official DEFAULT_OVERLAP +VIDEO_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 << 30 +KV_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() diff --git a/code/tt_depthpro2/cpu_engine.py b/code/tt_depthpro2/cpu_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..2dac99c16791a55eefe468146dcde29eaae3cf2e --- /dev/null +++ b/code/tt_depthpro2/cpu_engine.py @@ -0,0 +1,208 @@ +# 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 the +whole host pipeline -- the Python API, the video streaming and the HTTP server -- runs and is tested without a +device, against the official float32 goldens. ``DepthPro2.from_pretrained(..., backend="cpu")`` uses it; it is also +how 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 the +device 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 torch +from 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 = True diff --git a/code/tt_depthpro2/device.py b/code/tt_depthpro2/device.py new file mode 100644 index 0000000000000000000000000000000000000000..c1cb33d04704d1f846ac36c7035c3046a446780e --- /dev/null +++ b/code/tt_depthpro2/device.py @@ -0,0 +1,79 @@ +# 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-metal +44d6650 (the container image is built from a patched tree); if the ETH open fails, a ``RuntimeWarning`` is issued and +WORKER 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 same +dict), 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 the +model configuration: :func:`trace_region_for` sizes it from the configuration (``tt.model.trace_region_bytes``, from +the measured trace sizes) unless ``DEPTHPRO2_TRACE_REGION`` is set. Importing it has no side effects (``ttnn`` is +imported when a device is opened). +""" +from __future__ import annotations + +import contextlib +import dataclasses +import os +from 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.contextmanager +def 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) diff --git a/code/tt_depthpro2/io.py b/code/tt_depthpro2/io.py new file mode 100644 index 0000000000000000000000000000000000000000..bd8691265c785056df6d817d760387f82c2d2409 --- /dev/null +++ b/code/tt_depthpro2/io.py @@ -0,0 +1,251 @@ +# 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 to +8 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 base64 +import io +import math +import numbers +from pathlib import Path +from 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 = 16 +MAX_IMAGE_SIDE = 8192 +MAX_IMAGE_PIXELS = 50_000_000 +PNG_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": , "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 out diff --git a/code/tt_depthpro2/licenses/APPLE_MLR_MODEL_LICENSE.txt b/code/tt_depthpro2/licenses/APPLE_MLR_MODEL_LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..813ad18ca906a92d013a9c8fe332e5321e23d9e6 --- /dev/null +++ b/code/tt_depthpro2/licenses/APPLE_MLR_MODEL_LICENSE.txt @@ -0,0 +1,88 @@ +Disclaimer: IMPORTANT: This Apple Machine Learning Research Model is +specifically developed and released by Apple Inc. ("Apple") for the sole purpose +of scientific research of artificial intelligence and machine-learning +technology. “Apple Machine Learning Research Model” means the model, including +but not limited to algorithms, formulas, trained model weights, parameters, +configurations, checkpoints, and any related materials (including +documentation). + +This Apple Machine Learning Research Model is provided to You by +Apple in consideration of your agreement to the following terms, and your use, +modification, creation of Model Derivatives, and or redistribution of the Apple +Machine Learning Research Model constitutes acceptance of this Agreement. If You +do not agree with these terms, please do not use, modify, create Model +Derivatives of, or distribute this Apple Machine Learning Research Model or +Model 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. diff --git a/code/tt_depthpro2/licenses/APPLE_SOFTWARE_LICENSE.txt b/code/tt_depthpro2/licenses/APPLE_SOFTWARE_LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..18b48dc74c7b07ac9dee5c03dedffd527c133962 --- /dev/null +++ b/code/tt_depthpro2/licenses/APPLE_SOFTWARE_LICENSE.txt @@ -0,0 +1,47 @@ +Copyright (C) 2026 Apple Inc. All Rights Reserved. + +IMPORTANT: This Apple software is supplied to you by Apple +Inc. ("Apple") in consideration of your agreement to the following +terms, and your use, installation, modification or redistribution of +this Apple software constitutes acceptance of these terms. If you do +not agree with these terms, please do not use, install, modify or +redistribute this Apple software. + +In consideration of your agreement to abide by the following terms, and +subject to these terms, Apple grants you a personal, non-exclusive +license, under Apple's copyrights in this original Apple software (the +"Apple Software"), to use, reproduce, modify and redistribute the Apple +Software, with or without modifications, in source and/or binary forms; +provided that if you redistribute the Apple Software in its entirety and +without modifications, you must retain this notice and the following +text and disclaimers in all such redistributions of the Apple Software. +Neither the name, trademarks, service marks or logos of Apple Inc. may +be used to endorse or promote products derived from the Apple Software +without specific prior written permission from Apple. 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 rights that may be infringed by your derivative works or by other +works in which the Apple Software may be incorporated. + +The Apple Software is provided by Apple 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 SOFTWARE OR ITS USE AND +OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. + +IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL +OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, +MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, 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. + + +------------------------------------------------------------------------------- +SOFTWARE DISTRIBUTED IN THIS REPOSITORY: + +This software includes a number of subcomponents with separate +copyright notices and license terms - please see the file ACKNOWLEDGEMENTS. +------------------------------------------------------------------------------- diff --git a/code/tt_depthpro2/licenses/NOTICE.md b/code/tt_depthpro2/licenses/NOTICE.md new file mode 100644 index 0000000000000000000000000000000000000000..b5bde6aeb870f8599bcc862abea85346472ad0a3 --- /dev/null +++ b/code/tt_depthpro2/licenses/NOTICE.md @@ -0,0 +1,65 @@ +# 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 repository +above). 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 full +before 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`. diff --git a/code/tt_depthpro2/reference/__init__.py b/code/tt_depthpro2/reference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/tt_depthpro2/reference/model.py b/code/tt_depthpro2/reference/model.py new file mode 100644 index 0000000000000000000000000000000000000000..144bc5eb463c71dc6581155b8afcfd2ec9d3e692 --- /dev/null +++ b/code/tt_depthpro2/reference/model.py @@ -0,0 +1,427 @@ +# 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 no +dependency 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 the +device 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 json +import math +import os +from dataclasses import dataclass +from typing import Dict, List, Optional, Sequence, Tuple + +import numpy as np +import torch +from torch.nn import functional as F + +IMAGENET_MEAN = (0.485, 0.456, 0.406) +IMAGENET_STD = (0.229, 0.224, 0.225) +INPUT_MULTIPLE = 32 +PATCH = 16 +NUM_PREFIX = 5 # class token + 4 register tokens +HEAD_DIM = 64 +ROPE_TEMPERATURE = 100.0 +LN_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 = 248 +FOV_HEAD_HEADS = 4 +FOV_POOL = 2 +FOV_MAX_SHORT = 512 +FOV_MAX_ASPECT = 1.7778 +FOV_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) diff --git a/code/tt_depthpro2/samples/kropa_street/PROVENANCE.md b/code/tt_depthpro2/samples/kropa_street/PROVENANCE.md new file mode 100644 index 0000000000000000000000000000000000000000..7ed2a97bec9a84f0910a41177c5cd57bd62874d5 --- /dev/null +++ b/code/tt_depthpro2/samples/kropa_street/PROVENANCE.md @@ -0,0 +1,19 @@ +# 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) is +recorded in `sample.json` (`camera_f_px_at_640x480` = 462.25 px), for comparing the FOV estimate with the camera's +focal length; the image itself carries no EXIF, so the server estimates the focal length unless `f_px` is sent. + +`reference..json` / `reference..npy`: the float32 CPU reference output of this package for this image +at each model size (`scripts/make_sample_reference.py`; the npy is the focal-normalized inverse depth average-pooled +to 120 x 160, float16), against which `server/smoke_test.py` checks a served container. diff --git a/code/tt_depthpro2/samples/kropa_street/image.jpg b/code/tt_depthpro2/samples/kropa_street/image.jpg new file mode 100644 index 0000000000000000000000000000000000000000..10cc4185228a6f17b871de91f8475b95ae681f8c --- /dev/null +++ b/code/tt_depthpro2/samples/kropa_street/image.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dee4f3aafb7a1724d251e9af56ad9cd5eebbb95289ff63f4cdc1a2e0609445ae +size 126099 diff --git a/code/tt_depthpro2/samples/kropa_street/reference.B.json b/code/tt_depthpro2/samples/kropa_street/reference.B.json new file mode 100644 index 0000000000000000000000000000000000000000..3c946aef69ca8ff138855e13cb22575bf253dec6 --- /dev/null +++ b/code/tt_depthpro2/samples/kropa_street/reference.B.json @@ -0,0 +1,56 @@ +{ + "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 +} diff --git a/code/tt_depthpro2/samples/kropa_street/reference.B.npy b/code/tt_depthpro2/samples/kropa_street/reference.B.npy new file mode 100644 index 0000000000000000000000000000000000000000..abac100315666575c2a10b994a2c473d99ae9a19 --- /dev/null +++ b/code/tt_depthpro2/samples/kropa_street/reference.B.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:165d6a85312d039ab4de9b236dff8b53cbec3786faaa51d84863ce8de9d7b0b3 +size 38528 diff --git a/code/tt_depthpro2/samples/kropa_street/reference.H.json b/code/tt_depthpro2/samples/kropa_street/reference.H.json new file mode 100644 index 0000000000000000000000000000000000000000..7449845f153433a02d2c5fa8be4cf21dcb977a3a --- /dev/null +++ b/code/tt_depthpro2/samples/kropa_street/reference.H.json @@ -0,0 +1,56 @@ +{ + "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 +} diff --git a/code/tt_depthpro2/samples/kropa_street/reference.H.npy b/code/tt_depthpro2/samples/kropa_street/reference.H.npy new file mode 100644 index 0000000000000000000000000000000000000000..0808cc5dfee4b831a82ff8af8ea5f45ad235d918 --- /dev/null +++ b/code/tt_depthpro2/samples/kropa_street/reference.H.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4229120109053ab9e414325e7fdd9641006c9f447aeaaee0c790ad5e3642708 +size 38528 diff --git a/code/tt_depthpro2/samples/kropa_street/reference.L.json b/code/tt_depthpro2/samples/kropa_street/reference.L.json new file mode 100644 index 0000000000000000000000000000000000000000..27af8423c1c32deb4339b16f1f2080c6240ef8b6 --- /dev/null +++ b/code/tt_depthpro2/samples/kropa_street/reference.L.json @@ -0,0 +1,56 @@ +{ + "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 +} diff --git a/code/tt_depthpro2/samples/kropa_street/reference.L.npy b/code/tt_depthpro2/samples/kropa_street/reference.L.npy new file mode 100644 index 0000000000000000000000000000000000000000..0fdbea9d3d2bbeebb0c07a3518c34610419f54b6 --- /dev/null +++ b/code/tt_depthpro2/samples/kropa_street/reference.L.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7afe745115897a71ec3ea78e4383bc42f03f5252d27814f07199cd18627389c +size 38528 diff --git a/code/tt_depthpro2/samples/kropa_street/reference.S.json b/code/tt_depthpro2/samples/kropa_street/reference.S.json new file mode 100644 index 0000000000000000000000000000000000000000..401aee7b6feb1078ca3d55c5b6f708e5008768a9 --- /dev/null +++ b/code/tt_depthpro2/samples/kropa_street/reference.S.json @@ -0,0 +1,56 @@ +{ + "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 +} diff --git a/code/tt_depthpro2/samples/kropa_street/reference.S.npy b/code/tt_depthpro2/samples/kropa_street/reference.S.npy new file mode 100644 index 0000000000000000000000000000000000000000..e9b69f9f08665e911ae00553c703007555fea814 --- /dev/null +++ b/code/tt_depthpro2/samples/kropa_street/reference.S.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88434205fb9ed99fed257ffd6426bfc9007842ff08c86022310432cbb7740bd9 +size 38528 diff --git a/code/tt_depthpro2/samples/kropa_street/sample.json b/code/tt_depthpro2/samples/kropa_street/sample.json new file mode 100644 index 0000000000000000000000000000000000000000..37b847f9a564132a476878e25e81bd498e2adacc --- /dev/null +++ b/code/tt_depthpro2/samples/kropa_street/sample.json @@ -0,0 +1,11 @@ +{ + "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)" +} diff --git a/code/tt_depthpro2/server/__init__.py b/code/tt_depthpro2/server/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b3435063fabc92e00878ff1386919c9975de991 --- /dev/null +++ b/code/tt_depthpro2/server/__init__.py @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: Apache-2.0 +"""HTTP serving of DepthPro2: ``app.py`` (the ASGI app tt-model runs with uvicorn), ``client.py`` (stdlib request +builder and sender, runnable as a script), ``smoke_test.py`` (stdlib PASS / FAIL check of a running server: ETH +dispatch and the 12x10 grid asserted, the serve-profile pins, the depth of the shipped sample against its stored +CPU-reference output, the video route, and the 400 refusals).""" diff --git a/code/tt_depthpro2/server/app.py b/code/tt_depthpro2/server/app.py new file mode 100644 index 0000000000000000000000000000000000000000..c9c5e9f1f073652af50f91ad5d47f73eced48b26 --- /dev/null +++ b/code/tt_depthpro2/server/app.py @@ -0,0 +1,715 @@ +# 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 video +streams (``DEPTHPRO2_MAX_STREAMS``, or unbuffered beyond ``DEPTHPRO2_KV_STREAMS``), 503 before start-up completes, 500 ``inference failed: : ``. One lock serialises the +requests (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 the +chip opens; every bucket and clip length compiled and warmed), and only then let uvicorn print ``Application startup +complete``. A start-up failure raises (uvicorn exits non-zero; there is no CPU fallback). Shutdown closes the open +video streams and the model under the lock (SIGTERM, tt-model's 120 s grace) and logs ``Device closed``. Importing +this 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 size +repos' commits) and ``TT_MODEL_WEIGHTS_REVISION`` / ``TT_WEIGHTS_REVISION`` (the focal repo's commit), default the +pinned 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 json +import logging +import os +import threading +import time +from contextlib import asynccontextmanager +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, List, Literal, Mapping, Optional, Tuple + +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr + +from .. import __version__ +from .. import config as C +from .. import io as tio +from ..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_NAME +ENV_PREFIX = C.ENV_PREFIX +HARDWARE = "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") + + +@asynccontextmanager +async 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) diff --git a/code/tt_depthpro2/server/client.py b/code/tt_depthpro2/server/client.py new file mode 100644 index 0000000000000000000000000000000000000000..379f5b29ccce02b35de90adbab9ca2e986e2e3c5 --- /dev/null +++ b/code/tt_depthpro2/server/client.py @@ -0,0 +1,227 @@ +#!/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 argparse +import base64 +import json +import shutil +import struct +import subprocess +import sys +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence, Tuple + +HERE = Path(__file__).resolve().parent +SAMPLE_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()) diff --git a/code/tt_depthpro2/server/smoke_test.py b/code/tt_depthpro2/server/smoke_test.py new file mode 100644 index 0000000000000000000000000000000000000000..c8ae89944c18ce0fd7c87dd01c54469bdc997a6a --- /dev/null +++ b/code/tt_depthpro2/server/smoke_test.py @@ -0,0 +1,415 @@ +#!/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 /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..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 argparse +import ast +import base64 +import importlib.util +import json +import math +import struct +import sys +import time +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence, Tuple + +HERE = Path(__file__).resolve().parent +sys.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_NAME +ENV_PREFIX = C.ENV_PREFIX +EXPECT_DISPATCH, EXPECT_GRID = "eth", "12x10" # the p150 target; deliberately not a command-line option +SAMPLE_DIR = HERE.parent / "samples" / "kropa_street" +POOL = 4 +GATES = {"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(" 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()) diff --git a/code/tt_depthpro2/streaming.py b/code/tt_depthpro2/streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..8cb9b07aac9730e0825a52b2ede76516ac43078f --- /dev/null +++ b/code/tt_depthpro2/streaming.py @@ -0,0 +1,174 @@ +# 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 the +unbuffered 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 runs +the 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 the +official ``infer_video`` does. +""" +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass +from typing import Any, Callable, Deque, List, Optional + +import torch + +__all__ = ["StreamPrediction", "DepthStream", "blend_weights"] + + +@dataclass +class 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 out diff --git a/code/tt_depthpro2/tests/__init__.py b/code/tt_depthpro2/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4acb20c89ea7ecfdef46d7b2fbaa97fbdebcd84e --- /dev/null +++ b/code/tt_depthpro2/tests/__init__.py @@ -0,0 +1,3 @@ +# 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).""" diff --git a/code/tt_depthpro2/tests/baseline_helpers.py b/code/tt_depthpro2/tests/baseline_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..3f397834bd45297bc57f37f1543c8d299bb17cd9 --- /dev/null +++ b/code/tt_depthpro2/tests/baseline_helpers.py @@ -0,0 +1,161 @@ +# 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 json +import math +import os +from 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 = 32768 +TRACE_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/__.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}" diff --git a/code/tt_depthpro2/tests/conftest.py b/code/tt_depthpro2/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..7ad9b6470b7f4a4bf7db8c48a22a7928cd93c330 --- /dev/null +++ b/code/tt_depthpro2/tests/conftest.py @@ -0,0 +1,20 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Fixtures of the DepthPro2 tests (host and device). The package root (``code/``) is put on ``sys.path``; the host +tests' torch thread count is ``DEPTHPRO2_TEST_THREADS`` (default 8).""" +import os +import 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"))) diff --git a/code/tt_depthpro2/tests/emulate_bf16_drift.py b/code/tt_depthpro2/tests/emulate_bf16_drift.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e780f47f2cea5c3e7e4f1ba50a0e0b224355cd --- /dev/null +++ b/code/tt_depthpro2/tests/emulate_bf16_drift.py @@ -0,0 +1,93 @@ +# 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 reproduces +them to 6 digits (S img_vga / clip4_240x320: PCC, absrel_valid, p99, max_rel identical), so it stands in for the +official 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 argparse +import json +import os +import sys +import 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: E402 +from 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__)") + 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() diff --git a/code/tt_depthpro2/tests/host_helpers.py b/code/tt_depthpro2/tests/host_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..4fbda82d21bfa65569a7d35d9b58ab7d360b3042 --- /dev/null +++ b/code/tt_depthpro2/tests/host_helpers.py @@ -0,0 +1,99 @@ +# 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-engine +models, comparisons. Tests that need weights or goldens skip when they are absent. + +``DEPTHPRO2_TEST_WEIGHTS`` (a parent of ``DepthPro2-/`` and ``DepthPro2-focal/``; else ``DEPTHPRO2_WEIGHTS_DIR``, +else ``code/weights`` next to the package) and ``DEPTHPRO2_GOLDEN`` (Apple's float32 goldens, ``__.safetensors``; +default ``code/golden`` next to the package) say where they are. +""" +from __future__ import annotations + +import os +from pathlib import Path +from 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]) diff --git a/code/tt_depthpro2/tests/make_baseline_refs.py b/code/tt_depthpro2/tests/make_baseline_refs.py new file mode 100644 index 0000000000000000000000000000000000000000..4f3f08b1ed563e1b6cf636d8e0f2f4cf8ef4b41a --- /dev/null +++ b/code/tt_depthpro2/tests/make_baseline_refs.py @@ -0,0 +1,65 @@ +# 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's +input. Writes ``assets/depthpro2/baseline_ref/__.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 argparse +import json +import os +import sys +import 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 +from safetensors.torch import save_file # noqa: E402 + +import baseline_helpers as H # noqa: E402 +from 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() diff --git a/code/tt_depthpro2/tests/make_clip16_refs.py b/code/tt_depthpro2/tests/make_clip16_refs.py new file mode 100644 index 0000000000000000000000000000000000000000..817b0b7ffb90cf787697e3d3eee67c6be071853f --- /dev/null +++ b/code/tt_depthpro2/tests/make_clip16_refs.py @@ -0,0 +1,79 @@ +# 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 shorter +clip) for the VGA T=16 regression test of the device programs. The 16 distinct frames are built from the golden +480x640 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__.safetensors`` (+ .json): ``input_u8`` [16, 480, 640, 3], +``x_norm``, ``inverse_depth`` [16, 480, 640], ``inverse_depth_n`` [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 argparse +import json +import os +import sys +import 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 +from safetensors.torch import save_file # noqa: E402 + +import baseline_helpers as H # noqa: E402 +from 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() diff --git a/code/tt_depthpro2/tests/mk_dec_cmp.py b/code/tt_depthpro2/tests/mk_dec_cmp.py new file mode 100644 index 0000000000000000000000000000000000000000..85dfac7a276586614da5858973ad54d16db82c75 --- /dev/null +++ b/code/tt_depthpro2/tests/mk_dec_cmp.py @@ -0,0 +1,47 @@ +# 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 argparse +import os +import 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: E402 +from tt_depthpro2.tests import baseline_helpers as BH # noqa: E402 +from 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() diff --git a/code/tt_depthpro2/tests/mk_dec_diag.py b/code/tt_depthpro2/tests/mk_dec_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..8161af74d8b16571ccc499a5ff7403e586cc9a6e --- /dev/null +++ b/code/tt_depthpro2/tests/mk_dec_diag.py @@ -0,0 +1,78 @@ +# 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 device +taps with mk_dec, ttnn_dec and the float32 CPU reference decoder; report each decoder vs the reference decode of +those taps (pure DEC error) and the end-to-end metrics vs the golden. Saves the tensors under +assets/depthpro2/mk_dec_emu/diag____.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 argparse +import os +import 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: E402 +from tt_depthpro2.tests import baseline_helpers as BH # noqa: E402 +from tt_depthpro2.tt import StageShape # noqa: E402 +from 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() diff --git a/code/tt_depthpro2/tests/mk_dec_e2e.py b/code/tt_depthpro2/tests/mk_dec_e2e.py new file mode 100644 index 0000000000000000000000000000000000000000..db9c7fccbaa1277296058fb63fe2b8683283af34 --- /dev/null +++ b/code/tt_depthpro2/tests/mk_dec_e2e.py @@ -0,0 +1,92 @@ +# SPDX-License-Identifier: Apache-2.0 +"""End-to-end SPEC section 5 gates with the DEC megakernel: DepthPro2Device(engine enc=, dec=mk, fov=ttnn) on +the golden cases of the given sizes (inverse-depth PCC >= 0.999 -- >= 0.99 under the SPEC section 5 flat-scene rule, +golden valid inverse-depth cv < 0.15 --, depth AbsRel_valid <= max(2 x official bf16 drift, +0.01) with the baseline's emulated budgets for img_375x500_pad, repeat bit-exact). L / H img_375x500_pad use +assets/depthpro2/baseline_ref as the golden (baseline_helpers.golden_path). + + bin/devrun -t 3600 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_dec_e2e.py --sizes S,B,L,H \ + --enc ttnn +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import time + +import torch + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) + +from tt_depthpro2.reference import model as ref # noqa: E402 +from tt_depthpro2.tests import baseline_helpers as BH # noqa: E402 + +CASES = ("img_vga", "clip4_240x320", "img_375x500_pad") +LOG = os.path.join(BH.ROOT, "logs/depthpro2/mk_dec/e2e.jsonl") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--sizes", default="S") + ap.add_argument("--cases", default=",".join(CASES)) + ap.add_argument("--enc", default="ttnn") + ap.add_argument("--dec", default="mk") + args = ap.parse_args() + import ttnn + from tt_depthpro2.tt.model import DepthPro2Device + + dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), + l1_small_size=BH.L1_SMALL_SIZE, trace_region_size=BH.TRACE_REGION_SIZE) + allok = True + try: + for size in args.sizes.split(","): + w = ref.load_safetensors(os.path.join(BH.size_dir(size), "model.safetensors")) + cases = [c for c in args.cases.split(",") if BH.golden_path(c, size)] + golds = {c: BH.load_golden(c, size)[0] for c in cases} + for c in cases: + g = golds[c] + x = g["x_norm"] + t, _, h, wd = x.shape + bucket = tuple(ref.pad_to_multiple(x).shape[-2:]) + # one configuration per case (only the bucket / clip length the gate needs) + t0 = time.perf_counter() + m = DepthPro2Device(dev, size, w, None, buckets=[bucket], max_frames=t, + engine={"enc": args.enc, "dec": args.dec}) + build_s = time.perf_counter() - t0 + inv = m.inverse_depth(ref.pad_to_multiple(x))[:, :h, :wd] + t1 = time.perf_counter() + inv2 = m.inverse_depth(ref.pad_to_multiple(x))[:, :h, :wd] + call_ms = 1e3 * (time.perf_counter() - t1) + m.close() + del m + gref = g["inverse_depth"].reshape(t, h, wd) + met = BH.drift_metrics(inv, gref) + budget, why = BH.absrel_budget(c, size) + # SPEC section 5 flat-scene rule: golden valid inverse-depth cv (std / mean, valid = within 100x of the + # nearest point, as in metrics()) < 0.15 -> PCC is only a sanity floor (>= 0.99); AbsRel decides + gv = gref.double().flatten() + gv = gv[gv >= 0.01 * gv.max()] + cv = float(gv.std() / gv.mean()) + pcc_gate = 0.99 if cv < 0.15 else 0.999 + ok = met["pcc"] >= pcc_gate and met["absrel_valid"] <= budget and torch.equal(inv, inv2) + allok = allok and ok + rec = {"size": size, "case": c, "enc": args.enc, "dec": args.dec, + "golden": os.path.basename(os.path.dirname(BH.golden_path(c, size))), "pcc": met["pcc"], + "absrel": met["absrel_valid"], "delta1": met["delta1_valid"], "budget": budget, + "golden_cv": cv, "pcc_gate": pcc_gate, "flat_scene": cv < 0.15, + "budget_from": why, "repeat_bitexact": bool(torch.equal(inv, inv2)), "call_ms": call_ms, + "build_s": build_s, "passed": ok, "time": time.strftime("%Y-%m-%d %H:%M:%S")} + print(json.dumps(rec), flush=True) + os.makedirs(os.path.dirname(LOG), exist_ok=True) + with open(LOG, "a") as f: + f.write(json.dumps(rec) + "\n") + finally: + ttnn.close_device(dev) + print("ALL PASS" if allok else "SOME FAILED", flush=True) + + +if __name__ == "__main__": + main() diff --git a/code/tt_depthpro2/tests/mk_dec_emu.py b/code/tt_depthpro2/tests/mk_dec_emu.py new file mode 100644 index 0000000000000000000000000000000000000000..83b578f74bf54ca21e8a80d2e5150e1734a596e2 --- /dev/null +++ b/code/tt_depthpro2/tests/mk_dec_emu.py @@ -0,0 +1,281 @@ +# SPDX-License-Identifier: Apache-2.0 +"""CPU emulator of the DEC megakernel data path (tt/mk_dec): the exact storage layout of every map, the unit +decomposition, the band / tilize offsets and the weight-arena stream indexing of every layer, with the device's +arithmetic (bf16 operands, fp32 accumulation, bf16 maps). It is the reference the device kernels are debugged +against (per layer: the maps it produces must match the device's maps). + + python -m tt_depthpro2.tests.mk_dec_emu --size S --case img_384x512 +""" + +from __future__ import annotations + +import argparse +import os +import sys +import time +from typing import Dict, List, Optional + +import torch + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) + +from tt_depthpro2.tt.mk_dec import plan as P # noqa: E402 +from tt_depthpro2.tt.mk_dec import wprep as WP # noqa: E402 + +BF = torch.bfloat16 + + +def bf(t: torch.Tensor) -> torch.Tensor: + return t.to(BF).float() + + +class Emu: + def __init__(self, plan: P.Plan, w: Dict[str, torch.Tensor], arena: Optional[torch.Tensor] = None): + self.p = plan + self.arena = arena if arena is not None else WP.build_arena(plan.layers, w) + self.tiles = WP.untilize(self.arena.reshape(-1, 1024).float()).reshape(self.arena.shape[0], P.PAGE_TILES, 32, 32) + c = WP.const_tiles(w) + self.const = bf(c) + self.sel = WP.sel_tiles(plan.hp, plan.wp) + self.maps = [torch.zeros(m.frames, m.fpix, m.C) for m in plan.maps] + + # ------------------------------------------------------------------ weight stream + def wtile(self, L: P.Layer, nb: int, kb: int, idx: int) -> torch.Tensor: + pg = P.block_page(L, nb, kb) + return self.tiles[pg + idx // P.PAGE_TILES, idx % P.PAGE_TILES] + + def wblock(self, L: P.Layer, nb: int, kb: int) -> torch.Tensor: + pg = P.block_page(L, nb, kb) + npg = L.bp0 if kb == 0 else L.bp + return self.tiles[pg:pg + npg].reshape(-1, 32, 32) + + # ------------------------------------------------------------------ helpers + def gather_px(self, m: int, f: int, y: int, x0: int, n: int) -> torch.Tensor: + """n storage pixels from (y, x0) of map m, frame f: [n, C]""" + g = self.p.maps[m] + s = g.g(y, x0) + assert 0 <= s and s + n <= g.fpix, (g.name, y, x0, n) + return self.maps[m][f, s:s + n] + + def write_px(self, m: int, f: int, y: int, x: int, vals: torch.Tensor, c0: int = 0): + g = self.p.maps[m] + assert 0 <= y < g.H and 0 <= x and x + vals.shape[0] <= g.W, (g.name, y, x, vals.shape) + s = g.g(y, x) + self.maps[m][f, s:s + vals.shape[0], c0:c0 + vals.shape[1]] = bf(vals) + + # ------------------------------------------------------------------ ops + def run_layer(self, L: P.Layer, taps: List[torch.Tensor], grp: int, out: torch.Tensor): + if L.op == P.OP_RA: # per token tile (the device's RA units are output pages; same numerics) + for m in range(self.p.G * self.p.pt): + self.unit_ra(L, m, taps, grp) + return + for u in range(L.u): + if L.op == P.OP_UP: + self.unit_up(L, u) + else: + self.unit_c3(L, u, grp, out) + + def unit_ra(self, L: P.Layer, m0: int, taps, grp: int): + p = self.p + tap = taps[L.src] + kt = L.cin // 32 + dst = p.maps[L.dst] + for m in (m0,): + f, pi = m // p.pt, m % p.pt + row0 = (grp * p.G + f) * p.np_ + 32 * pi + A = tap[row0:row0 + 32] # [32, C] + for nb in range(L.n // L.nbw): + acc = torch.zeros(32, L.nbw * 32, dtype=torch.float64) + for kb in range(L.nkb): + blk = self.wblock(L, nb, kb).double() + off = L.nbias if kb == 0 else 0 + if kb == 0: + for n in range(L.nbw): + acc[:, 32 * n:32 * n + 32] += self.const[P.C_E01].double() @ blk[n] + for c in range(L.kc): + a = A[:, (kb * L.kc + c) * 32:(kb * L.kc + c) * 32 + 32].double() + for n in range(L.nbw): + acc[:, 32 * n:32 * n + 32] += a @ blk[off + c * L.nbw + n] + res = acc.float() + for r in range(32): + tok = 32 * pi + r + if tok >= p.n: + break + self.write_px(L.dst, f, tok // p.gw, tok % p.gw, res[r:r + 1], nb * L.nbw * 32) + + def unit_up(self, L: P.Layer, u: int): + p = self.p + src, dst = p.maps[L.src], p.maps[L.dst] + f, rem = divmod(u, L.yb * L.xb) + yb, xb = divmod(rem, L.xb) + y0, kx0 = yb * L.bh, xb * L.bw + bh, bw = min(L.bh, L.ho - y0), min(L.bw, L.kxo - kx0) + k = L.s + cout = L.n * 32 // (k * k) + for r in range(bh): + y = y0 + r + band = self.gather_px(L.src, f, y, 32 * kx0, 32 * bw) + for kx in range(bw): + A = band[32 * kx:32 * kx + 32].double() # [32, Cin] + x0 = 32 * (kx0 + kx) + for nb in range(L.n // L.nbw): + blk = self.wblock(L, nb, 0).double() + acc = torch.zeros(32, L.nbw * 32, dtype=torch.float64) + for n in range(L.nbw): + acc[:, 32 * n:32 * n + 32] += self.const[P.C_E01].double() @ blk[n] + for c in range(L.kc): + a = A[:, 32 * c:32 * c + 32] + for n in range(L.nbw): + acc[:, 32 * n:32 * n + 32] += a @ blk[L.nbias + c * L.nbw + n] + res = acc.float() + for rr in range(32): + x = x0 + rr + if x >= src.W: + break + for n in range(L.nbw): + ch = (nb * L.nbw + n) * 32 + gi, co = divmod(ch, cout) + a_, b_ = divmod(gi, k) + self.write_px(L.dst, f, k * y + a_, k * x + b_, res[rr:rr + 1, 32 * n:32 * n + 32], co) + + def unit_c3(self, L: P.Layer, u: int, grp: int, out: torch.Tensor): + p = self.p + src = p.maps[L.src] + s = L.s + f, rem = divmod(u, L.yb * L.xb) + yb, xb = divmod(rem, L.xb) + y0, kx0 = yb * L.bh, xb * L.bw + bh, bw = min(L.bh, L.ho - y0), min(L.bw, L.kxo - kx0) + rows = s * (bh - 1) + 3 + px = s * (32 * bw - 1) + 3 + band = torch.stack([self.gather_px(L.src, f, s * y0 - 1 + j, s * 32 * kx0 - 1, px) for j in range(rows)]) + if L.flags & P.F_RELU_IN: + band = band.clamp_min(0) + + def A(dx, j, kx, ct): + i0 = s * 32 * kx + 1 + dx + return band[j, i0:i0 + s * 32:s, 32 * ct:32 * ct + 32].double() + + hc = L.op == P.OP_HC + nb_cnt = L.n // L.nbw + for nb in range(nb_cnt): + acc = torch.zeros(bh, bw, 32, L.nbw * 32, dtype=torch.float64) + for kb in range(L.nkb): + blk = self.wblock(L, nb, kb).double() + off = L.nbias if kb == 0 else 0 + for r in range(bh): + for kx in range(bw): + a_acc = acc[r, kx] + if kb == 0: + for n in range(L.nbw): + if hc: + y = y0 + r + ycls = 0 if y == 0 else (2 if y == L.ho - 1 else 1) + sel = self.sel[ycls * p.kx_hc + kx0 + kx].double() + a_acc[:, 32 * n:32 * n + 32] += sel @ blk[n] + else: + a_acc[:, 32 * n:32 * n + 32] += self.const[P.C_E01].double() @ blk[n] + for c in range(L.kc): + ct = kb * L.kc + c + if hc: + for n in range(4): + a_, b_ = divmod(n, 2) + for o in range(4): + oy, ox = a_ - 1 + o // 2, b_ - 1 + o % 2 + a_acc[:, 32 * n:32 * n + 32] += A(ox, r + 1 + oy, kx, ct) @ blk[off + (c * 4 + n) * 4 + o] + else: + for t in range(9): + dy, dx = t // 3 - 1, t % 3 - 1 + a = A(dx, s * r + 1 + dy, kx, ct) + for n in range(L.nbw): + a_acc[:, 32 * n:32 * n + 32] += a @ blk[off + (c * 9 + t) * L.nbw + n] + # residuals (added in fp32: bf16 maps) + for rm in L.res: + for r in range(bh): + for kx in range(bw): + x0 = 32 * (kx0 + kx) + rv = self.gather_px(rm, f, y0 + r, x0, 32)[:, nb * L.nbw * 32:(nb + 1) * L.nbw * 32] + acc[r, kx] += rv.double() + res = acc.float() + if L.flags & P.F_RELU_OUT: + res = res.clamp_min(0) + for r in range(bh): + y = y0 + r + for kx in range(bw): + x0 = 32 * (kx0 + kx) + nv = min(32, L.wo - x0) + if hc: + z = bf(res[r, kx].clamp_min(0)).double() # relu(head.2) -> bf16 (CB_Z) + R = torch.zeros(32, 32, dtype=torch.float64) + for sb in range(4): + zs = z[:, 32 * sb:32 * sb + 32] + R += (self.const[P.C_W4H + sb].double() + self.const[P.C_W4L + sb].double()) @ zs.t() + R += self.const[P.C_E4].double() @ self.const[P.C_B4T].double().t() + R = R.float().clamp_min(0) + fr = grp * p.G + f + for a_ in range(2): + for b_ in range(2): + out[fr, 2 * y + a_, 2 * x0 + b_:2 * (x0 + nv):2] = R[2 * a_ + b_, :nv] + else: + self.write_px(L.dst, f, y, x0, res[r, kx, :nv], nb * L.nbw * 32) + + def run(self, taps: List[torch.Tensor], nl: Optional[int] = None) -> torch.Tensor: + p = self.p + taps = [bf(t.reshape(-1, t.shape[-1])) for t in taps] + out = torch.zeros(p.T, p.hp, p.wp) + for grp in range(p.ngrp): + for li, L in enumerate(p.layers): + if nl is not None and li >= nl: + break + self.run_layer(L, taps, grp, out) + return out + + def map_image(self, name: str, f: int = 0) -> torch.Tensor: + """map ``name`` of frame f as [C, H, W] (interior)""" + g = next(m for m in self.p.maps if m.name == name) + st = self.maps[g.idx][f] + img = torch.stack([st[g.g(y, 0):g.g(y, 0) + g.W] for y in range(g.H)]) # [H, W, C] + return img.permute(2, 0, 1) + + +def golden_taps(g, n_p: int) -> List[torch.Tensor]: + out = [] + for i in range(4): + t = g[f"tap{i}"].float() + T, N, C = t.shape + z = torch.zeros(T, n_p, C) + z[:, :N] = t + out.append(z.reshape(T * n_p, C)) + return out + + +def main(): + from tt_depthpro2.reference import model as R + from tt_depthpro2.tests import baseline_helpers as BH + + ap = argparse.ArgumentParser() + ap.add_argument("--size", default="S") + ap.add_argument("--case", default="img_384x512") + args = ap.parse_args() + torch.set_num_threads(8) + w = R.load_safetensors(os.path.join(BH.size_dir(args.size), "model.safetensors")) + g, _ = BH.load_golden(args.case, args.size) + x = R.pad_to_multiple(g["x_norm"]) + T, _, hp, wp = x.shape + t0 = time.time() + plan = P.Plan(args.size, T, hp, wp, 12, 10) + emu = Emu(plan, w) + inv = emu.run(golden_taps(g, plan.np_)) + ref = g["head.out"][:, 0] + print(f"emu {time.time() - t0:.1f} s: inv pcc {BH.pcc(inv, ref):.7f} max_rel {BH.max_rel(inv, ref):.2e}") + for i, nm in enumerate(("P0", "P1", "P2", "P3")): + d = emu.map_image(nm) + gr = g[f"reassemble{i}"][0] + d = d[:gr.shape[0]] + print(f" reassemble{i}: pcc {BH.pcc(d, gr):.7f} max_rel {BH.max_rel(d, gr):.2e}") + d = emu.map_image("Z0") + print(f" decoder.out: pcc {BH.pcc(d, g['decoder.out'][0]):.7f} max_rel {BH.max_rel(d, g['decoder.out'][0]):.2e}") + + +if __name__ == "__main__": + main() diff --git a/code/tt_depthpro2/tests/mk_dec_run.py b/code/tt_depthpro2/tests/mk_dec_run.py new file mode 100644 index 0000000000000000000000000000000000000000..a90d36d889061fe737a64defffd0e32a32b20d39 --- /dev/null +++ b/code/tt_depthpro2/tests/mk_dec_run.py @@ -0,0 +1,235 @@ +# SPDX-License-Identifier: Apache-2.0 +"""DEC megakernel bring-up / debug run on one golden case: the stage on the golden taps vs the float32 golden +``head.out`` (and the CPU emulator's maps, layer by layer), optional trace timing and replay determinism. + + bin/devrun -t 900 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_dec_run.py --size S \ + --case img_384x512 [--nl N] [--maps] [--reps 20] +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import time + +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: E402 +from tt_depthpro2.tests import baseline_helpers as BH # noqa: E402 +from tt_depthpro2.tests import mk_dec_emu as EMU # noqa: E402 +from tt_depthpro2.tt.mk_dec import plan as P # noqa: E402 + +EMU_DIR = os.path.join(BH.ROOT, "assets/depthpro2/mk_dec_emu") +LOG = os.path.join(BH.ROOT, "logs/depthpro2/mk_dec/runs.jsonl") + + +def emu_maps(size: str, case: str, plan: P.Plan, w, g): + os.makedirs(EMU_DIR, exist_ok=True) + # _pa: page-aligned map rows (storage layout of round 7) + path = os.path.join(EMU_DIR, f"{case}__{size}__{plan.hp}x{plan.wp}_T{plan.T}_G{plan.G}_pa.pt") + if os.path.exists(path): + return torch.load(path, weights_only=True) + t0 = time.time() + emu = EMU.Emu(plan, w) + inv = emu.run(EMU.golden_taps(g, plan.np_)) + out = {"inv": inv, **{m.name: emu.maps[m.idx] for m in plan.maps}} + torch.save(out, path) + print(f"emulator {time.time() - t0:.0f} s -> {path}", flush=True) + return out + + +def rand_taps(size: str, T: int, hp: int, wp: int, seed: int = 0): + """taps [T, N, C] with DINOv3-like scale (per-channel spread), deterministic (tests/mk_dec_cmp.py uses the same)""" + gen = torch.Generator().manual_seed(seed) + n = (hp // 16) * (wp // 16) + c = R.SIZES[size].dim + out = [] + for i in range(4): + sc = torch.rand(c, generator=gen) * 2.0 + 0.25 + out.append(torch.randn(T, n, c, generator=gen) * sc) + return out + + +def print_prof(mk): + """per layer: wall time (hub barrier exits), max core work time, TRISC split (max over cores, us)""" + pf = mk.read_prof().double() # [NC, PROF_WORDS] ticks + clk = 1.0e3 # wall-clock ticks per us (Blackhole: 1 GHz reference) + names = [L.name for L in mk.plan.layers] + prev = 0.0 + tot = {k: 0.0 for k in ("wall", "barrier", "wwait", "inwait", "tilize", "mm", "epi")} + print(f"{'layer':8s} {'wall':>7s} {'work':>7s} {'bar':>6s} | trisc max: {'w_wait':>7s} {'in_wait':>7s} " + f"{'tilize':>7s} {'mm':>7s} {'epi':>7s} (us)") + for l, nm in enumerate(names[:32]): + done = pf[:, 8 * l + 0].max().item() / clk + bar = pf[0, 8 * l + 1].item() / clk + sl = [pf[:, 8 * l + k].max().item() / clk for k in range(2, 7)] + wall = bar - prev + tot["wall"] += wall + tot["barrier"] += bar - done + for k, v in zip(("wwait", "inwait", "tilize", "mm", "epi"), sl): + tot[k] += v + print(f"{nm:8s} {wall:7.1f} {done - prev:7.1f} {bar - done:6.1f} | {sl[0]:16.1f} {sl[1]:7.1f} {sl[2]:7.1f} " + f"{sl[3]:7.1f} {sl[4]:7.1f}") + prev = bar + print("totals (us): " + ", ".join(f"{k} {v:.0f}" for k, v in tot.items()), flush=True) + + +def show_aborts(mk, ab, n=12): + """abort codes per core (md_defs.hpp AB_*; 7 = released by another RISC of the core), exit-barrier timeouts""" + for i, wv in ab[:n]: + print(f" core {i} (x {i % mk.grid[0]}, y {i // mk.grid[0]}): brisc {wv[0]}/{wv[1]} ncrisc {wv[2]}/{wv[3]} " + f"unpack {wv[4]}/{wv[5]} pack {wv[6]}/{wv[7]} layer {wv[8]} exit-bits {wv[10]}", flush=True) + if ab: + codes = {} + for _, wv in ab: + k = tuple(wv[j] for j in (0, 2, 4, 6)) + codes[k] = codes.get(k, 0) + 1 + print(f" abort-code histogram (brisc, ncrisc, unpack, pack): {codes}", flush=True) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--size", default="S") + ap.add_argument("--case", default="img_384x512") + ap.add_argument("--nl", type=int, default=None) + ap.add_argument("--maps", action="store_true", help="compare every map with the CPU emulator") + ap.add_argument("--reps", type=int, default=0, help="trace replays for timing / determinism") + ap.add_argument("--eager", type=int, default=0, help="extra eager runs (no trace), each checked for aborts / equality") + ap.add_argument("--fid", default="HiFi4") + ap.add_argument("--dump", default="", help="save the device storage of these maps (comma list, 'all') to EMU_DIR") + ap.add_argument("--prof", action="store_true", help="profiling build (MD_PROF): per-layer timing table") + ap.add_argument("--dispatch", default="eth", choices=("eth", "worker"), + help="dispatch cores: eth (12x10 grid, default) or worker (11x10)") + ap.add_argument("--shape", default="", help="HxWxT: random taps (seed 0) instead of a golden case; the output is " + "saved for tests/mk_dec_cmp.py (CPU reference decode of the same taps)") + args = ap.parse_args() + torch.set_num_threads(8) + import ttnn + + from tt_depthpro2.tt.mk_dec.program import MkDec, MkDecWeights + + w = R.load_safetensors(os.path.join(BH.size_dir(args.size), "model.safetensors")) + if args.shape: + hp, wp, T = (int(v) for v in args.shape.split("x")) + args.case = f"rand_{hp}x{wp}x{T}" + g = {f"tap{i}": t for i, t in enumerate(rand_taps(args.size, T, hp, wp))} + g["head.out"] = None + else: + g, _ = BH.load_golden(args.case, args.size) + x = R.pad_to_multiple(g["x_norm"]) + T, _, hp, wp = x.shape + dct = ttnn.DispatchCoreType.ETH if args.dispatch == "eth" else ttnn.DispatchCoreType.WORKER + dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(dct), + l1_small_size=32768, trace_region_size=16 << 20) + rec = {"size": args.size, "case": args.case, "T": T, "hp": hp, "wp": wp, "fid": args.fid, "dispatch": args.dispatch, + "time": time.strftime("%Y-%m-%d %H:%M:%S")} + try: + t0 = time.perf_counter() + wts = MkDecWeights(dev, w, args.size) + mk = MkDec(dev, wts, args.size, T, hp, wp, fidelity=args.fid, + defines=[("MD_PROF", "1")] if args.prof else ()) + print(mk.plan.summary(), flush=True) + print(f"weights {wts.dram_bytes / 2**20:.1f} MB, L1 {mk.l1_bytes() / 1024:.0f} KB, prep {time.perf_counter() - t0:.1f} s", + flush=True) + n_p = mk.plan.np_ + taps = [] + for i in range(4): + t = g[f"tap{i}"].float() + z = torch.zeros(T, n_p, t.shape[-1]) + z[:, :t.shape[1]] = t + taps.append(ttnn.from_torch(z.reshape(1, 1, T * n_p, -1).to(torch.bfloat16), dtype=ttnn.bfloat16, + layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG)) + t0 = time.perf_counter() + out = mk.run(taps, nl=args.nl) + ttnn.synchronize_device(dev) + rec["first_run_s"] = time.perf_counter() - t0 + ab = mk.aborts() + rec["aborts"] = len(ab) + print(f"first run {rec['first_run_s']:.1f} s; aborted cores {len(ab)}", flush=True) + show_aborts(mk, ab) + inv = ttnn.to_torch(out).float().reshape(T, hp, wp) + rec["finite"] = bool(torch.isfinite(inv).all()) + if args.shape: + os.makedirs(EMU_DIR, exist_ok=True) + path = os.path.join(EMU_DIR, f"dev_{args.case}__{args.size}.pt") + torch.save({"inv": inv}, path) + print(f"saved {path} finite {rec['finite']} (compare: tests/mk_dec_cmp.py)", flush=True) + elif args.nl is None: + ref = g["head.out"][:, 0] + rec["inv_pcc"] = BH.pcc(inv, ref) + rec["inv_max_rel"] = BH.max_rel(inv, ref) + print(f"inv vs golden: pcc {rec['inv_pcc']:.7f} max_rel {rec['inv_max_rel']:.3e} finite {rec['finite']}", + flush=True) + if args.maps: + em = emu_maps(args.size, args.case, mk.plan, w, g) + nl = len(mk.plan.layers) if args.nl is None else args.nl + done = {mk.plan.layers[i].dst for i in range(nl) if mk.plan.layers[i].dst >= 0} + res = {} + for m in mk.plan.maps: + if m.idx not in done: + continue + d = mk.read_storage(m.name) + e = em[m.name] + # interior only + mask = torch.zeros(m.fpix, dtype=torch.bool) + for yy in range(m.H): + mask[m.g(yy, 0):m.g(yy, 0) + m.W] = True + dd, ee = d[:, mask], e[:, mask] + pads_ok = bool((d[:, ~mask] == 0).all()) + res[m.name] = (BH.pcc(dd, ee), BH.max_rel(dd, ee), pads_ok) + print(f" map {m.name:4s} pcc {res[m.name][0]:.7f} max_rel {res[m.name][1]:.2e} pads_zero {pads_ok}", + flush=True) + if args.nl is None: + print(f" inv vs emu: pcc {BH.pcc(inv, em['inv']):.7f} max_rel {BH.max_rel(inv, em['inv']):.2e}") + rec["maps"] = res + if args.dump: + names = [m.name for m in mk.plan.maps] if args.dump == "all" else args.dump.split(",") + dump = {nm: mk.read_storage(nm) for nm in names} + dump["inv"] = inv + path = os.path.join(EMU_DIR, f"dev_{args.case}__{args.size}.pt") + torch.save(dump, path) + print(f"dumped {names} -> {path}", flush=True) + for i in range(args.eager): + t0 = time.perf_counter() + o3 = mk.run(taps, nl=args.nl) + ttnn.synchronize_device(dev) + same = torch.equal(ttnn.to_torch(o3).float().reshape(T, hp, wp), inv) + ab = mk.aborts() + print(f"eager rerun {i + 1}: {1e3 * (time.perf_counter() - t0):.1f} ms, aborted cores {len(ab)}, " + f"bit-exact {same}", flush=True) + show_aborts(mk, ab) + ttnn.deallocate(o3) + if args.prof: + print_prof(mk) + if args.reps: + raw = inv.clone() + tid = ttnn.begin_trace_capture(dev, cq_id=0) + o2 = mk.run(taps, nl=args.nl) + ttnn.end_trace_capture(dev, tid, cq_id=0) + ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) + t0 = time.perf_counter() + for _ in range(args.reps): + ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) + ttnn.synchronize_device(dev) + rec["dec_ms"] = 1e3 * (time.perf_counter() - t0) / args.reps + same = torch.equal(ttnn.to_torch(o2).float().reshape(T, hp, wp), raw) + rec["replay_bitexact"] = same + ab = mk.aborts() + rec["aborts_after_trace"] = len(ab) + show_aborts(mk, ab) + ttnn.release_trace(dev, tid) + print(f"trace: {rec['dec_ms']:.3f} ms / run, replay bit-exact {same}, aborted cores after the replays " + f"{rec['aborts_after_trace']}", flush=True) + finally: + ttnn.close_device(dev) + os.makedirs(os.path.dirname(LOG), exist_ok=True) + with open(LOG, "a") as f: + f.write(json.dumps({k: v for k, v in rec.items() if k != "maps"}) + "\n") + + +if __name__ == "__main__": + main() diff --git a/code/tt_depthpro2/tests/mk_enc_bench.py b/code/tt_depthpro2/tests/mk_enc_bench.py new file mode 100644 index 0000000000000000000000000000000000000000..27952f72f97bfabcd0652570e6cb68cc7a103f89 --- /dev/null +++ b/code/tt_depthpro2/tests/mk_enc_bench.py @@ -0,0 +1,96 @@ +# SPDX-License-Identifier: Apache-2.0 +"""ENC megakernel device time per (size, shape) under trace (the configs of code/scripts/bench_baseline.py), weights +uploaded once per size (MkEncWeights) and shared by every shape; finiteness and replay determinism checked. + + bin/devrun -t 3600 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_bench.py --sizes S,B \ + --configs 480x640x1,256x320x4,480x640x4,480x640x16,736x1280x1,1088x1920x1 +""" + +from __future__ import annotations + +import argparse +import gc +import json +import os +import sys +import time + +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: E402 +from tt_depthpro2.tests import mk_enc_ref as H # noqa: E402 +from tt_depthpro2.tt.mk_enc import arena as A # noqa: E402 +from tt_depthpro2.tt.mk_enc.program import MkEnc, MkEncWeights # noqa: E402 + +LOG = "/home/ubuntu/experiments/tt-models/logs/depthpro2/mk_enc/bench.jsonl" + + +def frames(hp: int, wp: int, T: int) -> torch.Tensor: + g = H.load_case("img_vga", "S") + x = torch.nn.functional.interpolate(g["x_norm"].float(), size=(hp, wp), mode="bilinear", align_corners=False) + gen = torch.Generator().manual_seed(0) + x = x.repeat(T, 1, 1, 1) + return x + 0.1 * torch.randn(x.shape, generator=gen) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--sizes", default="S") + ap.add_argument("--configs", default="480x640x1") + ap.add_argument("--reps", type=int, default=5) + ap.add_argument("--mode", default="depth") + args = ap.parse_args() + import ttnn + + dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), + trace_region_size=16 << 20) + try: + for size in args.sizes.split(","): + w = H.load_weights("fov" if args.mode == "fov" else size) + t0 = time.perf_counter() + wts = MkEncWeights(dev, w, size, args.mode) + up = time.perf_counter() - t0 + print(f"{size}: weights {wts.dram_bytes / 2**20:.0f} MB uploaded in {up:.1f} s", flush=True) + for cfg in args.configs.split(","): + hp, wp, T = (int(v) for v in cfg.split("x")) + x = frames(hp, wp, T) + patches = ttnn.from_torch(A.patchify(x).to(torch.bfloat16).reshape(1, 1, -1, 768), + dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev, + memory_config=ttnn.DRAM_MEMORY_CONFIG) + t0 = time.perf_counter() + mk = MkEnc(dev, wts, size, T, hp // 16, wp // 16, mode=args.mode) + print(f"RUN {size} {hp}x{wp}x{T}: {mk.geo.summary()}", flush=True) + mk.run(patches) + ttnn.synchronize_device(dev) + first = time.perf_counter() - t0 + raw = [ttnn.to_torch(t).clone() for t in mk.taps] + fin = all(bool(torch.isfinite(r.float()).all()) for r in raw) + tid = ttnn.begin_trace_capture(dev, cq_id=0) + mk.run(patches) + ttnn.end_trace_capture(dev, tid, cq_id=0) + ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) + t0 = time.perf_counter() + for _ in range(args.reps): + ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) + ttnn.synchronize_device(dev) + ms = 1e3 * (time.perf_counter() - t0) / args.reps + same = all(torch.equal(a, ttnn.to_torch(t)) for a, t in zip(raw, mk.taps)) + ttnn.release_trace(dev, tid) + rec = {"size": size, "mode": args.mode, "hp": hp, "wp": wp, "T": T, "enc_ms": ms, + "first_run_s": first, "finite": fin, "replays_bitexact": same, "geometry": mk.geo.summary(), + "time": time.strftime("%Y-%m-%d %H:%M:%S")} + print(json.dumps(rec), flush=True) + with open(LOG, "a") as f: + f.write(json.dumps(rec) + "\n") + del mk, patches, raw + gc.collect() + del wts + gc.collect() + finally: + ttnn.close_device(dev) + + +if __name__ == "__main__": + main() diff --git a/code/tt_depthpro2/tests/mk_enc_e2e.py b/code/tt_depthpro2/tests/mk_enc_e2e.py new file mode 100644 index 0000000000000000000000000000000000000000..7dcb56465c6b6d3dd4be222e86825974c2de5da9 --- /dev/null +++ b/code/tt_depthpro2/tests/mk_enc_e2e.py @@ -0,0 +1,88 @@ +# SPDX-License-Identifier: Apache-2.0 +"""End-to-end SPEC section 5 gates with the ENC megakernel: DepthPro2Device(engine enc=mk, dec / fov = ttnn) on the +golden cases of the given sizes (inverse-depth PCC >= 0.999 -- >= 0.99 on flat scenes, golden valid inverse-depth +cv < 0.15, SPEC §5 flat-scene rule --, depth AbsRel <= max(2 x official bf16 drift, 0.01), repeat bit-exact). + + bin/devrun -t 3600 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_e2e.py --sizes S,B,L,H +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import time + +import torch + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) + +from tt_depthpro2.reference import model as ref # noqa: E402 +from tt_depthpro2.tests import baseline_helpers as BH # noqa: E402 + +CASES = ("img_vga", "clip4_240x320", "img_375x500_pad") +LOG = "/home/ubuntu/experiments/tt-models/logs/depthpro2/mk_enc/e2e.jsonl" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--sizes", default="S") + ap.add_argument("--cases", default=",".join(CASES)) + ap.add_argument("--enc", default="mk") + ap.add_argument("--fov", default="ttnn", help="FOV engine (mk: tt/mk_fov); f_px vs the golden is gated too") + args = ap.parse_args() + import ttnn + from tt_depthpro2.tt.model import DepthPro2Device + + dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), + l1_small_size=BH.L1_SMALL_SIZE, trace_region_size=BH.TRACE_REGION_SIZE) + fw = ref.load_safetensors(os.path.join(BH.fov_dir(), "model.safetensors")) + allok = True + try: + for size in args.sizes.split(","): + w = ref.load_safetensors(os.path.join(BH.size_dir(size), "model.safetensors")) + cases = [c for c in args.cases.split(",") if BH.golden_path(c, size)] + golds = {c: BH.load_golden(c, size)[0] for c in cases} + buckets = sorted({tuple(ref.pad_to_multiple(g["x_norm"]).shape[-2:]) for g in golds.values()}) + t0 = time.perf_counter() + m = DepthPro2Device(dev, size, w, fw, buckets=buckets, max_frames=1, engine={"enc": args.enc, "fov": args.fov}) + print(f"{size}: built in {time.perf_counter() - t0:.1f} s (enc={args.enc}, fov={args.fov})", flush=True) + for c in cases: + g = golds[c] + x = g["x_norm"] + t, _, h, wd = x.shape + inv = m.inverse_depth(ref.pad_to_multiple(x))[:, :h, :wd] + t1 = time.perf_counter() + inv2 = m.inverse_depth(ref.pad_to_multiple(x))[:, :h, :wd] + call_ms = 1e3 * (time.perf_counter() - t1) + met = BH.drift_metrics(inv, g["inverse_depth"].reshape(t, h, wd)) + budget, why = BH.absrel_budget(c, size) + gi = g["inverse_depth"].double().flatten() + gv = gi[gi >= 0.01 * gi.max()] + cv = float(gv.std() / gv.mean()) + pcc_gate = 0.99 if cv < 0.15 else 0.999 # SPEC §5 flat-scene rule + ok = met["pcc"] >= pcc_gate and met["absrel_valid"] <= budget and torch.equal(inv, inv2) + y = ref.fov_resize(x) + deg = ref.fov_logits_to_deg(m.fov_logits(y), (h, wd), tuple(y.shape[-2:])) + f_px = float(ref.median_focal_length_px(deg, h, wd)) + f_rel = abs(f_px / float(g["focallength_px"]) - 1) + f_budget, _ = BH.fov_budget(c) + ok = ok and f_rel <= f_budget + allok = allok and ok + rec = {"size": size, "case": c, "enc": args.enc, "pcc": met["pcc"], "pcc_gate": pcc_gate, "cv": cv, + "absrel": met["absrel_valid"], "delta1": met["delta1_valid"], "fov": args.fov, "f_rel": f_rel, + "f_budget": f_budget, + "budget": budget, "budget_from": why, "repeat_bitexact": bool(torch.equal(inv, inv2)), + "call_ms": call_ms, "passed": ok, "time": time.strftime("%Y-%m-%d %H:%M:%S")} + print(json.dumps(rec), flush=True) + with open(LOG, "a") as f: + f.write(json.dumps(rec) + "\n") + m.close() + finally: + ttnn.close_device(dev) + print("ALL PASS" if allok else "SOME FAILED", flush=True) + + +if __name__ == "__main__": + main() diff --git a/code/tt_depthpro2/tests/mk_enc_ref.py b/code/tt_depthpro2/tests/mk_enc_ref.py new file mode 100644 index 0000000000000000000000000000000000000000..9c4554f331d5d11e34d48fddf927f34c2e946c4b --- /dev/null +++ b/code/tt_depthpro2/tests/mk_enc_ref.py @@ -0,0 +1,148 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Host-side helpers of the ENC megakernel tests: weights / golden loading, the float32 reference (embed, blocks, +per-block q / k / v / attention output) and the mapping between reference tokens ``[T, 5 + N, C]`` and the +megakernel's row tiles ``[Mt, 32, C]`` (geometry.py: prefix tiles, then patch tiles, then the pool tile).""" + +from __future__ import annotations + +import os +from typing import Dict, List, Optional, Tuple + +import torch +import torch.nn.functional as F + +from tt_depthpro2.reference import model as R + +ROOT = "/home/ubuntu/experiments/tt-models" +GOLDEN = os.path.join(ROOT, "assets/depthpro2/golden") +WEIGHTS = "/mnt/chang/models/apple/DepthPro2-{}/model.safetensors" +P = R.NUM_PREFIX + + +def load_weights(size: str) -> Dict[str, torch.Tensor]: + return R.load_safetensors(WEIGHTS.format("focal" if size == "fov" else size)) + + +def load_case(case: str, size: str) -> Dict[str, torch.Tensor]: + """The official golden, else the clean-room float32 reference output (``make_baseline_refs.py``, no taps).""" + from safetensors.torch import load_file + + p = os.path.join(GOLDEN, f"{case}__{size}.safetensors") + if not os.path.exists(p): + p = os.path.join(ROOT, "assets/depthpro2/baseline_ref", f"{case}__{size}.safetensors") + return load_file(p) + + +def pcc(a: torch.Tensor, b: torch.Tensor) -> float: + a, b = a.double().flatten(), b.double().flatten() + a, b = a - a.mean(), b - b.mean() + return float((a @ b) / (a.norm() * b.norm() + 1e-30)) + + +def rel_err(a: torch.Tensor, b: torch.Tensor) -> float: + return float((a.double() - b.double()).norm() / (b.double().norm() + 1e-30)) + + +# ------------------------------------------------------------------------------------------------ token mapping +def to_internal(tokens: torch.Tensor, geo) -> torch.Tensor: + """``[T, 5 + N, C]`` -> ``[Mt, 32, C]`` (pool tile and padding rows zero).""" + t, _, c = tokens.shape + out = torch.zeros(geo.Mt, 32, c) + out[:t, :P] = tokens[:, :P] + pt = torch.zeros(t, geo.Np, c) + pt[:, :geo.N] = tokens[:, P:] + out[t:t + t * geo.Pt] = pt.reshape(t * geo.Pt, 32, c) + return out + + +def from_internal(xi: torch.Tensor, geo) -> torch.Tensor: + """``[Mt, 32, C]`` -> ``[T, 5 + N, C]``.""" + t, c = geo.T, xi.shape[-1] + pre = xi[:t, :P] + pat = xi[t:t + t * geo.Pt].reshape(t, geo.Np, c)[:, :geo.N] + return torch.cat([pre, pat], 1) + + +def taps_from_device(tap: torch.Tensor, geo) -> torch.Tensor: + """depth-mode tap ``[T * Np, C]`` -> ``[T, N, C]``; fov mode ``[T * (32 + Np), C]`` -> ``[T, 5 + N, C]``.""" + t, c = geo.T, tap.shape[-1] + if geo.mode == "fov": + x = tap.reshape(t, 32 + geo.Np, c) + return torch.cat([x[:, :P], x[:, 32:32 + geo.N]], 1) + return tap.reshape(t, geo.Np, c)[:, :geo.N] + + +# ------------------------------------------------------------------------------------------------ reference +def cfg_of(size: str, mode: str) -> R.SizeConfig: + return R.FOV_TRUNK if mode == "fov" else R.SIZES[size] + + +def ref_embed(w, x: torch.Tensor, mode: str) -> torch.Tensor: + return R.embed(x, w, "trunk." if mode == "fov" else "encoder.") + + +def ref_block(tokens, w, l: int, cfg, rope, mode: str) -> torch.Tensor: + pfx = "trunk." if mode == "fov" else "encoder." + p = f"{pfx}blocks.{l}" + if mode == "fov": + out = R.block(tokens, w, p, cfg, rope) + if l in cfg.cross_frame_blocks: + out = torch.cat([tokens[:, :P], out[:, P:]], dim=1) + return out + if l in cfg.cross_frame_blocks: + return R.cross_frame_block(tokens, w, p, cfg, rope) + return R.block(tokens, w, p, cfg, rope) + + +def ref_run(w, x: torch.Tensor, size: str, nl: int, mode: str = "depth") -> Tuple[torch.Tensor, List[torch.Tensor]]: + """tokens after ``nl`` blocks and the taps (depth: patch tokens; fov: all tokens) of the blocks run.""" + cfg = cfg_of(size, mode) + grid = (x.shape[-2] // 16, x.shape[-1] // 16) + rope = R.rope_table(*grid) + tok = ref_embed(w, x, mode) + taps = [] + with torch.no_grad(): + for l in range(nl): + tok = ref_block(tok, w, l, cfg, rope, mode) + if l in cfg.reassembled_blocks: + taps.append(tok if mode == "fov" else tok[:, P:]) + return tok, taps + + +def ref_qkv(tokens, w, l: int, size: str, mode: str, gh: int, gw: int) -> Dict[str, torch.Tensor]: + """q (x 1/8) / k / v of block ``l`` (post RoPE) as ``[Mt-like tokens]``: dict of ``[T, 5 + N, C]`` (joint blocks: + prefix rows hold the pool tile's k / v in row-tile ``Mt - 1``, returned separately as ``pool_k`` / ``pool_v``).""" + cfg = cfg_of(size, mode) + pfx = "trunk." if mode == "fov" else "encoder." + p = f"{pfx}blocks.{l}" + sin, cos = R.rope_table(gh, gw) + t = tokens.shape[0] + with torch.no_grad(): + q, k, v = R.block_qkv(tokens, w, p, cfg.heads, (sin, cos), P) # (T, h, L, d) + out = {n: a.permute(0, 2, 1, 3).reshape(t, a.shape[2], -1) for n, a in (("q", q / 8.0), ("k", k), ("v", v))} + joint = mode == "depth" and l in cfg.cross_frame_blocks + if joint: + pool = tokens[:, :P].mean(0, keepdim=True) + pq, pk, pv = R.block_qkv(pool, w, p, cfg.heads, None, P) + out["pool_k"] = pk.permute(0, 2, 1, 3).reshape(1, P, -1)[0] + out["pool_v"] = pv.permute(0, 2, 1, 3).reshape(1, P, -1)[0] + return out + + +def ref_attn(tokens, w, l: int, size: str, mode: str, gh: int, gw: int) -> torch.Tensor: + """attention output (heads merged, before proj) of block ``l``: ``[T, 5 + N, C]`` (joint: prefix rows 0).""" + cfg = cfg_of(size, mode) + pfx = "trunk." if mode == "fov" else "encoder." + p = f"{pfx}blocks.{l}" + sin, cos = R.rope_table(gh, gw) + t, n, c = tokens.shape + with torch.no_grad(): + if mode == "depth" and l in cfg.cross_frame_blocks: + x = torch.cat([tokens[:, :P].mean(0, keepdim=True), tokens[:, P:].reshape(1, -1, c)], 1) + q, k, v = R.block_qkv(x, w, p, cfg.heads, (sin.repeat(t, 1), cos.repeat(t, 1)), P) + a = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(1, -1, c) + out = torch.zeros(t, n, c) + out[:, P:] = a[0, P:].reshape(t, -1, c) + return out + q, k, v = R.block_qkv(tokens, w, p, cfg.heads, (sin, cos), P) + return F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(t, n, c) diff --git a/code/tt_depthpro2/tests/mk_enc_run.py b/code/tt_depthpro2/tests/mk_enc_run.py new file mode 100644 index 0000000000000000000000000000000000000000..b1c8943c391bd5ee085833b28a0ec9df03a9c116 --- /dev/null +++ b/code/tt_depthpro2/tests/mk_enc_run.py @@ -0,0 +1,258 @@ +# SPDX-License-Identifier: Apache-2.0 +"""ENC megakernel device runner (debug / bring-up): run the program for ``--nl`` blocks on a golden case and compare +x (fp32 dump), q / k / v of block nl and the attention output of block nl - 1 with the float32 reference. + + bin/devrun -t 900 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_run.py --size S \ + --case img_384x512 --nl 1 +""" + +from __future__ import annotations + +import argparse +import os +import sys +import time + +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: E402 +from tt_depthpro2.tests import mk_enc_ref as H # noqa: E402 +from tt_depthpro2.tt.mk_enc import arena as A # noqa: E402 +from tt_depthpro2.tt.mk_enc.program import MkEnc # noqa: E402 + + +def open_device(dispatch: str = "eth", trace: bool = False): + import ttnn + + kw = {"trace_region_size": 8 << 20} if trace else {} + if dispatch == "eth": + kw["dispatch_core_config"] = ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH) + return ttnn.open_device(device_id=0, **kw) + + +def report(name, dev, ref, geo=None): + print(f" {name:12s} pcc {H.pcc(dev, ref):.6f} rel {H.rel_err(dev, ref):.3e} max|d| " + f"{(dev - ref).abs().max().item():.3e} max|ref| {ref.abs().max().item():.3e}", flush=True) + + +def prof_report(p, geo, nl): + """per-phase times (us at 1.35 GHz... the stamps are AICLK cycles) from the BRISC / TRISC stamps of every core""" + clk = 1350.0 + t0 = p[:, 0].min() + rel = lambda i: (p[:, i] - t0).double() / clk # noqa: E731 + print(f"PROF E phase: {rel(1).max().item():.1f} us (from boot)") + tot_a = tot_w = tot_b = 0.0 + for l in range(nl): + a0, a1, w0, w1 = (rel(2 + 4 * l + k) for k in range(4)) + ta = (a1 - a0).max().item() + tw = (w1 - w0).max().item() + tb = (w0 - a1).max().item() + tot_a, tot_w, tot_b = tot_a + ta, tot_w + tw, tot_b + tb + tri = ((p[:, 193 + 2 * l] - p[:, 192 + 2 * l]).double() / clk) + print(f"PROF blk {l:2d}: att {ta:8.1f} (trisc max {tri.max().item():8.1f} mean {tri.mean().item():8.1f}) " + f"barrier {tb:6.1f} wave {tw:8.1f} us; end {rel(5 + 4 * l).max().item():9.1f}") + print(f"PROF total: att {tot_a:.1f} wave {tot_w:.1f} barrier {tot_b:.1f} us") + if nl > 1: # block 1, wave 0 detail (relative to the TRISC's wave start, per core then max / mean) + base = p[:, 256].double() + names = {257: "proj end", 258: "stats_out(LN2) end", 259: "fc1 end", 260: "fc2 end", 261: "tail (LN1+QKV) end", + 262: "fc1: INX landed", 263: "fc1: stats_in done", 264: "proj: INF landed", 265: "fc2: INF landed", + 266: "qkv: INX landed", 267: "qkv: stats_in done"} + for i, n in names.items(): + d = (p[:, i].double() - base) / clk + print(f"PROF w1 trisc {n:22s}: max {d.max().item():7.1f} mean {d.mean().item():7.1f} us") + ab = p[:, 384].double() + ok = (p[:, 384:390] > 0).all(1) & ((p[:, 389].double() - ab) > 0) & ((p[:, 389].double() - ab) < 1e7) + if ok.any(): + for i, n in {385: "S packed", 386: "rowmax", 387: "m_new", 388: "P packed", 389: "PV done"}.items(): + d = ((p[:, i].double() - ab) / clk)[ok] + print(f"PROF att item (q0, c0) {n:10s}: max {d.max().item():7.1f} mean {d.mean().item():7.1f} us " + f"({int(ok.sum())} cores)") + bb = p[:, 320].double() + for i, n in {321: "IA gather done", 322: "LN2 gather done", 323: "FC1 gather done", 324: "tail done"}.items(): + d = (p[:, i].double() - bb) / clk + print(f"PROF w1 brisc {n:22s}: max {d.max().item():7.1f} mean {d.mean().item():7.1f} us") + + +def probe_report(prb, w, x, args, geo, gh, gw): + """item 0 of block 0 (head 0, q = prefix tile of frame 0): S16 0..1, M, MFN 0..1, AP 0..1, ST 0..3 (chunk 0), + M, MFN 0..1, ST 0..3 (chunk 1)""" + tok0, _ = H.ref_run(w, x, args.size, 0, args.mode) + rq = H.ref_qkv(tok0, w, 0, args.size, args.mode, gh, gw) + qi = H.to_internal(rq["q"], geo)[:, :, :64] + ki = H.to_internal(rq["k"], geo)[:, :, :64] + vi = H.to_internal(rq["v"], geo)[:, :, :64] + keys = [0] + list(range(geo.T, geo.T + geo.Pt)) + mask = torch.zeros(32, 32) + mask[:, 5:] = -1e9 + S = [qi[0] @ ki[k].T + (mask if k < geo.T else 0) for k in keys] + kc = geo.kc + m0 = torch.stack(S[:kc], 0).amax(0).amax(-1) + P0 = [torch.exp(s - m0[:, None]) for s in S[:kc]] + O0 = sum(p @ vi[k] for p, k in zip(P0, keys[:kc])) + l0 = sum(p.sum(-1) for p in P0) + names = ["S16_0", "S16_1", "M_c0", "mnew_c0", "alpha_c0", "P_0", "P_1", "O0_c0", "O1_c0", "l_c0", "m_c0", + "M_c1", "mnew_c1", "alpha_c1", "O0_c1", "O1_c1", "l_c1", "m_c1"] + ref = {"S16_0": S[0], "S16_1": S[1], "M_c0": m0, "mnew_c0": m0[:, None].expand(32, 32), "P_0": P0[0], + "P_1": P0[1], "O0_c0": O0[:, :32], "O1_c0": O0[:, 32:], "l_c0": l0[:, None].expand(32, 32), + "m_c0": m0[:, None].expand(32, 32)} + for i, n in enumerate(names): + d = prb[i] + line = f" probe {i:2d} {n:9s} dev[0,:4] {d[0, :4].tolist()} dev[5,:2] {d[5, :2].tolist()}" + if n in ref: + r = ref[n] + if r.dim() == 1: + line += f" | ref[0] {r[0].item():.4g} ref[5] {r[5].item():.4g}" + else: + line += f" | ref[0,:4] {[round(v, 4) for v in r[0, :4].tolist()]}" + print(line, flush=True) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--size", default="S") + ap.add_argument("--case", default="img_384x512") + ap.add_argument("--mode", default="depth") + ap.add_argument("--nl", type=int, default=0) + ap.add_argument("--frames", type=int, default=0, help="use the first n frames of the case (0: all)") + ap.add_argument("--rb", type=int, default=0) + ap.add_argument("--qb", type=int, default=0) + ap.add_argument("--kc", type=int, default=32) + ap.add_argument("--fidelity", default="HiFi4") + ap.add_argument("--reps", type=int, default=1) + ap.add_argument("--dispatch", default="eth") + ap.add_argument("--probe", action="store_true") + ap.add_argument("--colerr", action="store_true") + ap.add_argument("--resize", type=int, nargs=2, default=None, help="bilinear resize to H W (multiples of 32)") + ap.add_argument("--tframes", type=int, default=0, help="clip of n frames: repeat the case's frames + noise") + ap.add_argument("--noref", action="store_true", help="skip the CPU reference (timing runs)") + ap.add_argument("--det", type=int, default=0, help="rerun n times and compare x / q / k / v / o bitwise") + ap.add_argument("--prof", action="store_true", help="ME_PROF build: per-phase device time stamps") + ap.add_argument("--bench", type=int, default=0, help="trace replays to time (full model, nl = L)") + args = ap.parse_args() + import ttnn + + gsize = "S" if args.mode == "fov" else args.size + g = H.load_case(args.case, gsize) + x = R.pad_to_multiple(g["x_norm"].float()) + if args.frames: + x = x[:args.frames] + if args.mode == "fov": + x = R.fov_resize(g["x_norm"].float()) + if args.resize: + x = torch.nn.functional.interpolate(x, size=tuple(args.resize), mode="bilinear", align_corners=False) + if args.tframes: + gen = torch.Generator().manual_seed(0) + reps = -(-args.tframes // x.shape[0]) + x = x.repeat(reps, 1, 1, 1)[:args.tframes] + x = x + 0.1 * torch.randn(x.shape, generator=gen) + x = torch.roll(x, shifts=1, dims=-1) if False else x + T, _, hp, wp = x.shape + gh, gw = hp // 16, wp // 16 + w = H.load_weights("fov" if args.mode == "fov" else args.size) + dev = open_device(args.dispatch, trace=args.bench > 0) + try: + t0 = time.perf_counter() + mk = MkEnc(dev, w, args.size, T, gh, gw, mode=args.mode, rb=args.rb, qb=args.qb, kc=args.kc, + fidelity=args.fidelity, probe=args.probe, prof=args.prof) + geo = mk.geo + print(geo.summary(), f"init {time.perf_counter() - t0:.1f}s", flush=True) + patches = ttnn.from_torch(A.patchify(x).to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, + device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) + nl = args.nl + for r in range(args.reps): + t0 = time.perf_counter() + mk.run(patches, nl=nl, dump=True) + ttnn.synchronize_device(dev) + print(f"run {r}: {1e3 * (time.perf_counter() - t0):.2f} ms", flush=True) + if args.bench: + for _ in range(2): + mk.run(patches, nl=nl, dump=True) + ttnn.synchronize_device(dev) + tid = ttnn.begin_trace_capture(dev, cq_id=0) + mk.run(patches, nl=nl, dump=True) + ttnn.end_trace_capture(dev, tid, cq_id=0) + ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) + t0 = time.perf_counter() + for _ in range(args.bench): + ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) + ttnn.synchronize_device(dev) + dt = (time.perf_counter() - t0) / args.bench + print(f"BENCH {geo.summary()} nl={nl}: {1e3 * dt:.3f} ms / run (trace, {args.bench} replays)", flush=True) + ttnn.release_trace(dev, tid) + xi = mk.read_x() + qd, kd, vd, od = (mk.read_stage(n) for n in "qkvo") + taps0 = [ttnn.to_torch(t).float().reshape(-1, geo.dim) for t in mk.taps] + for r in range(args.det): + mk.run(patches, nl=nl, dump=True) + ttnn.synchronize_device(dev) + diffs = [] + for n, a in (("x", xi), ("q", qd), ("k", kd), ("v", vd), ("o", od)): + b = mk.read_x() if n == "x" else mk.read_stage(n) + if not torch.equal(a, b): + d = (a != b).reshape(geo.Mt, 32, -1).any(1).any(-1).nonzero().flatten().tolist() + diffs.append(f"{n}: row tiles {d[:12]} ({len(d)}) max|d| {(a - b).abs().max().item():.3e}") + for i, t in enumerate(mk.taps): + b = ttnn.to_torch(t).float().reshape(-1, geo.dim) + a = taps0[i] + if not torch.equal(a, b): + d = (a != b).reshape(-1, 32, geo.dim).any(1).any(-1).nonzero().flatten().tolist() + diffs.append(f"tap{i}: tiles {d[:12]} ({len(d)}) max|d| {(a - b).abs().max().item():.3e}") + print(f"DET rerun {r}: " + ("identical" if not diffs else "; ".join(diffs)), flush=True) + dtaps = [H.taps_from_device(ttnn.to_torch(t).float(), geo) for t in mk.taps] + prb = mk.read_probe() if args.probe else None + if args.prof: + prof_report(mk.read_prof(), geo, nl) + finally: + ttnn.close_device(dev) + if args.noref: + return + for n, d in (("q", qd), ("k", kd), ("v", vd), ("o", od), ("x", xi)): + bad = ~torch.isfinite(d) + if bad.any(): + per = bad.reshape(geo.Mt, 32, -1, 64).any(1).any(-1) # [Mt, heads] + print(f" non-finite {n}: {int(bad.sum())} values; row tiles x heads:\n{per.int()}", flush=True) + print(f" {n} finite sample row tile 0 head 0: {d[0, :6, :4]}") + tok, taps = H.ref_run(w, x, args.size, nl, args.mode) + if prb is not None: + probe_report(prb, w, x, args, geo, gh, gw) + print(f"x after {nl} blocks:") + for i, tp in enumerate(taps): + gk = f"tap{i}" + if args.mode == "depth" and gk in g and nl == geo.L and not (args.frames or args.resize or args.tframes): + report(f"tap{i} gold", dtaps[i], g[gk].float()) + report(f"tap{i} ref", dtaps[i], tp) + xd = H.from_internal(xi, geo) + report("x prefix", xd[:, :5], tok[:, :5]) + report("x patches", xd[:, 5:], tok[:, 5:]) + if args.colerr: + e = (xd[:, 5:] - tok[:, 5:]).abs().reshape(-1, xd.shape[-1] // 32, 32).amax((0, 2)) + r = tok[:, 5:].abs().reshape(-1, xd.shape[-1] // 32, 32).amax((0, 2)) + print(" x patches max|d| per tile column:", [round(v, 3) for v in e.tolist()]) + print(" x patches max|ref| per tile column:", [round(v, 3) for v in r.tolist()]) + pe = (xd[:, 5:] - tok[:, 5:]).abs().amax(-1)[0] + bad = (pe > 0.1 * tok[:, 5:].abs().amax()).nonzero().flatten() + print(" bad patch rows:", bad[:40].tolist(), "count", bad.numel()) + if nl < geo.L: + rq = H.ref_qkv(tok, w, nl, args.size, args.mode, gh, gw) + joint = args.mode == "depth" and nl in geo.joint + for n, d in (("q", qd), ("k", kd), ("v", vd)): + dd = H.from_internal(d, geo) + report(f"{n} patches", dd[:, 5:], rq[n][:, 5:]) + if not joint: + report(f"{n} prefix", dd[:, :5], rq[n][:, :5]) + if joint and geo.pool: + report("pool k", kd[geo.Mt - 1, :5], rq["pool_k"]) + report("pool v", vd[geo.Mt - 1, :5], rq["pool_v"]) + if nl >= 1: + tin, _ = H.ref_run(w, x, args.size, nl - 1, args.mode) + ra = H.ref_attn(tin, w, nl - 1, args.size, args.mode, gh, gw) + oo = H.from_internal(od, geo) + report("attn patches", oo[:, 5:], ra[:, 5:]) + if not (nl - 1 in geo.freeze): + report("attn prefix", oo[:, :5], ra[:, :5]) + + +if __name__ == "__main__": + main() diff --git a/code/tt_depthpro2/tests/mk_enc_serve_repro.py b/code/tt_depthpro2/tests/mk_enc_serve_repro.py new file mode 100644 index 0000000000000000000000000000000000000000..5c944110a40fb2f3968df314df75fbb7176ece76 --- /dev/null +++ b/code/tt_depthpro2/tests/mk_enc_serve_repro.py @@ -0,0 +1,99 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Regression (serve-pkg device smoke, 2026-11-28 22:14): DepthPro2Device built as api.py builds it for the S server +with enc=mk -- buckets 480x640 / 640x480 / 256x320, window 4 (max_frames 4, frames (1,)), FOV shapes, clip lengths +(1, 4), KV cache on -- then images on every bucket, the golden 4-frame 240x320 clip, n = 2 / 3 frame clips on every +bucket (runtime valid-frame count of the T = 4 programs) vs the float32 reference, and a few unbuffered (ttnn KV) +steps in between; finally the golden clip again (no state leaks between programs). + + bin/devrun -t 2400 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_serve_repro.py [--enc mk] +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys + +import torch + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) + +from tt_depthpro2.reference import model as ref # noqa: E402 +from tt_depthpro2.tests import baseline_helpers as BH # noqa: E402 + + +def run_repro(dev, size: str = "S", enc: str = "mk", fov: str = "ttnn") -> bool: + """The serve-configuration regression on an open device (``l1_small_size`` >= 32 KB, trace region >= 224 MB).""" + from tt_depthpro2.tt.model import DepthPro2Device + + sw = ref.load_safetensors(os.path.join(BH.size_dir(size), "model.safetensors")) + fw = ref.load_safetensors(os.path.join(BH.fov_dir(), "model.safetensors")) + cpu = ref.DepthPro2Reference(size, sw) + buckets = [(480, 640), (640, 480), (256, 320)] + fov_shapes = sorted({DepthPro2Device.fov_size(h, w) for h, w in buckets}) + ok = True + + def check(name, inv, r, pcc_gate=0.999, absrel=0.01): + nonlocal ok + met = BH.drift_metrics(inv, r) + good = met["pcc"] >= pcc_gate and met["absrel_valid"] <= absrel + ok = ok and good + print(json.dumps({"check": name, "pcc": met["pcc"], "absrel": met["absrel_valid"], "passed": good}), flush=True) + + m = DepthPro2Device(dev, size, sw, fw, buckets, 4, engine={"enc": enc, "fov": fov}, frames=(1,), + fov_shapes=fov_shapes, clip_lengths=(1, 4), kv_cache=True) + try: + print("configurations:", m.configurations(), flush=True) + gc4, _ = BH.load_golden("clip4_240x320", size) + x4 = gc4["x_norm"].float() + T4, _, h4, w4 = x4.shape + + def golden_clip(tag): + inv = m.inverse_depth(ref.pad_to_multiple(x4))[:, :h4, :w4] + check(f"golden clip4 {tag}", inv, gc4["inverse_depth"].reshape(T4, h4, w4), + absrel=BH.absrel_budget("clip4_240x320", size)[0]) + + golden_clip("first") + gi, _ = BH.load_golden("img_vga", size) + xi = gi["x_norm"].float() + inv = m.inverse_depth(ref.pad_to_multiple(xi))[:, :480, :640] + check("golden img_vga", inv, gi["inverse_depth"].reshape(1, 480, 640)) + gen = torch.Generator().manual_seed(0) + for (bh, bw) in buckets: + base = torch.nn.functional.interpolate(xi, size=(bh, bw), mode="bilinear", align_corners=False) + clip = base.repeat(3, 1, 1, 1) + 0.05 * torch.randn(3, 3, bh, bw, generator=gen) + for n in (1, 2, 3): + inv = m.inverse_depth(clip[:n]) + with torch.no_grad(): + r = cpu.decode(*cpu.encode(clip[:n]))[:, 0] + check(f"bucket {bh}x{bw} n={n}", inv, r) + golden_clip(f"after bucket {bh}x{bw}") + cache = m.kv_cache((256, 320), 4) # unbuffered (ttnn KV step programs) in between + for t in range(3): + m.inverse_depth_step(ref.pad_to_multiple(x4[t:t + 1]), cache) + golden_clip("after kv steps") + finally: + m.close() + return ok + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--size", default="S") + ap.add_argument("--enc", default="mk") + ap.add_argument("--fov", default="ttnn") + args = ap.parse_args() + import ttnn + + dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), + l1_small_size=BH.L1_SMALL_SIZE, trace_region_size=224 << 20) + try: + ok = run_repro(dev, args.size, args.enc, args.fov) + finally: + ttnn.close_device(dev) + print("SERVE REPRO PASS" if ok else "SERVE REPRO FAIL", flush=True) + + +if __name__ == "__main__": + main() diff --git a/code/tt_depthpro2/tests/mk_enc_soak.py b/code/tt_depthpro2/tests/mk_enc_soak.py new file mode 100644 index 0000000000000000000000000000000000000000..8ae60c4c6533ff20d1d16d6c937c75bc85ae589b --- /dev/null +++ b/code/tt_depthpro2/tests/mk_enc_soak.py @@ -0,0 +1,107 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Soak of one ENC megakernel configuration (release gate, 2026-11-29): ``--eager`` eager launches (taps bitwise vs +the first), then one trace and ``--replays`` replays, each checked on the device against the first replay's taps +(``ttnn.ne`` + sum per tap: an exact mismatch count; +-0 compare equal). Appends to logs/depthpro2/mk_enc/soak.jsonl. + + bin/devrun -t 300 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_soak.py --size S --hw 480 640 --T 1 + (--mode fov: the FOV trunk; --size is then ignored) +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import time + +import torch + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) + +from tt_depthpro2.tests import mk_enc_ref as H # noqa: E402 +from tt_depthpro2.tt.mk_enc import arena as A # noqa: E402 +from tt_depthpro2.tt.mk_enc.program import MkEnc, MkEncWeights # noqa: E402 + +LOG = "/home/ubuntu/experiments/tt-models/logs/depthpro2/mk_enc/soak.jsonl" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--size", default="S") + ap.add_argument("--hw", type=int, nargs=2, default=(480, 640)) + ap.add_argument("--T", type=int, default=1) + ap.add_argument("--mode", default="depth") + ap.add_argument("--eager", type=int, default=10) + ap.add_argument("--replays", type=int, default=1000) + args = ap.parse_args() + import ttnn + + size = "S" if args.mode == "fov" else args.size + (hp, wp), T = args.hw, args.T + rec = {"size": "fov-trunk" if args.mode == "fov" else size, "mode": args.mode, "hp": hp, "wp": wp, "T": T, + "eager": args.eager, "replays": args.replays, "start": time.strftime("%Y-%m-%d %H:%M:%S")} + g = H.load_case("img_vga", "S") + x = torch.nn.functional.interpolate(g["x_norm"].float(), size=(hp, wp), mode="bilinear", align_corners=False) + x = x.repeat(T, 1, 1, 1) + 0.1 * torch.randn(T, 3, hp, wp, generator=torch.Generator().manual_seed(0)) + dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), + trace_region_size=16 << 20) + try: + wts = MkEncWeights(dev, H.load_weights("fov" if args.mode == "fov" else size), size, args.mode) + patches = ttnn.from_torch(A.patchify(x).to(torch.bfloat16).reshape(1, 1, -1, 768), dtype=ttnn.bfloat16, + layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) + mk = MkEnc(dev, wts, size, T, hp // 16, wp // 16, mode=args.mode) + rec["geometry"] = mk.geo.summary() + print("SOAK", rec["geometry"], flush=True) + first = None + bad_eager = 0 + t0 = time.perf_counter() + for i in range(args.eager): + mk.run(patches) + out = [ttnn.to_torch(t) for t in mk.taps] + if first is None: + first = out + elif not all(torch.equal(a, b) for a, b in zip(first, out)): + bad_eager += 1 + rec["eager_s"] = time.perf_counter() - t0 + rec["eager_mismatches"] = bad_eager + rec["finite"] = all(bool(torch.isfinite(t.float()).all()) for t in first) + tid = ttnn.begin_trace_capture(dev, cq_id=0) + mk.run(patches) + ttnn.end_trace_capture(dev, tid, cq_id=0) + ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) + ref = [ttnn.clone(t, memory_config=ttnn.DRAM_MEMORY_CONFIG) for t in mk.taps] + rec["first_replay_equals_eager"] = all(torch.equal(a, ttnn.to_torch(t)) for a, t in zip(first, ref)) + bad, worst = 0, 0 + t0 = time.perf_counter() + for r in range(args.replays): + ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) + n = 0 + for t, f in zip(mk.taps, ref): + ne = ttnn.ne(t, f, memory_config=ttnn.DRAM_MEMORY_CONFIG) + s = ttnn.sum(ne) + n += int(round(float(ttnn.to_torch(s).float().sum()))) + ttnn.deallocate(ne) + ttnn.deallocate(s) + if n: + bad += 1 + worst = max(worst, n) + print(f"replay {r}: {n} mismatching values", flush=True) + if (r + 1) % 100 == 0: + print(f"replay {r + 1}: {bad} mismatching replays so far", flush=True) + rec["replay_s"] = time.perf_counter() - t0 + rec["replay_ms_incl_check"] = 1e3 * rec["replay_s"] / max(1, args.replays) + rec["replay_mismatches"] = bad + rec["replay_worst_values"] = worst + ttnn.release_trace(dev, tid) + rec["passed"] = bad == 0 and bad_eager == 0 and rec["first_replay_equals_eager"] and rec["finite"] + finally: + rec["end"] = time.strftime("%Y-%m-%d %H:%M:%S") + print("REC " + json.dumps(rec), flush=True) + with open(LOG, "a") as f: + f.write(json.dumps(rec) + "\n") + ttnn.close_device(dev) + + +if __name__ == "__main__": + main() diff --git a/code/tt_depthpro2/tests/mk_enc_sweep.py b/code/tt_depthpro2/tests/mk_enc_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..fe8bc4e93e83c118eede8681fb500b91aa74258f --- /dev/null +++ b/code/tt_depthpro2/tests/mk_enc_sweep.py @@ -0,0 +1,164 @@ +# SPDX-License-Identifier: Apache-2.0 +"""One ENC configuration per call (run each through its own short devrun job): the megakernel's traced device time, +trace bytes, DRAM bytes, finiteness and replay determinism, and its taps vs the ttnn ENC engine on the same patches +(eager); the ttnn baseline's traced time from logs/depthpro2/baseline/bench*.jsonl. Out-of-memory / L1-budget +failures are recorded, not raised. Appends to logs/depthpro2/mk_enc/sweep.jsonl. + + bin/devrun -t 900 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_sweep.py --size L --hw 736 1280 --T 4 +""" + +from __future__ import annotations + +import argparse +import gc +import json +import os +import sys +import time +import traceback + +import torch + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) + +from tt_depthpro2.tests import mk_enc_ref as H # noqa: E402 +from tt_depthpro2.tt import StageShape # noqa: E402 +from tt_depthpro2.tt.mk_enc import arena as A # noqa: E402 +from tt_depthpro2.tt.mk_enc.program import MkEnc, MkEncWeights # noqa: E402 + +ROOT = "/home/ubuntu/experiments/tt-models" +LOG = os.path.join(ROOT, "logs/depthpro2/mk_enc/sweep.jsonl") + + +def baseline_ms(size, hp, wp, T): + best = None + for f in ("bench.jsonl", "bench_r2.jsonl"): + p = os.path.join(ROOT, "logs/depthpro2/baseline", f) + if not os.path.exists(p): + continue + for line in open(p): + d = json.loads(line) + if d.get("size") == size and (d.get("hp"), d.get("wp"), d.get("T")) == (hp, wp, T) and "enc_ms" in d: + best = (d["enc_ms"], d.get("enc_trace_mb")) + return best + + +def frames(hp, wp, T): + g = H.load_case("img_vga", "S") + x = torch.nn.functional.interpolate(g["x_norm"].float(), size=(hp, wp), mode="bilinear", align_corners=False) + gen = torch.Generator().manual_seed(0) + x = x.repeat(T, 1, 1, 1) + return x + 0.1 * torch.randn(x.shape, generator=gen) + + +def mem_mb(device, kind): + 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 main(): + ap = argparse.ArgumentParser() + ap.add_argument("--size", required=True) + ap.add_argument("--hw", type=int, nargs=2, required=True) + ap.add_argument("--T", type=int, required=True) + ap.add_argument("--reps", type=int, default=3) + ap.add_argument("--no-ttnn", action="store_true") + args = ap.parse_args() + import ttnn + + size, (hp, wp), T = args.size, args.hw, args.T + rec = {"size": size, "hp": hp, "wp": wp, "T": T} + bl = baseline_ms(size, hp, wp, T) + if bl: + rec["ttnn_enc_ms"], rec["ttnn_enc_trace_mb"] = bl + dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), + trace_region_size=64 << 20) + try: + w = H.load_weights(size) + d0 = mem_mb(dev, "dram") + wts = MkEncWeights(dev, w, size, "depth") + rec["weights_mb"] = mem_mb(dev, "dram") - d0 + x = frames(hp, wp, T) + pt = A.patchify(x).to(torch.bfloat16).reshape(1, 1, -1, 768) + patches = ttnn.from_torch(pt, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev, + memory_config=ttnn.DRAM_MEMORY_CONFIG) + d1 = mem_mb(dev, "dram") + t0 = time.perf_counter() + try: + mk = MkEnc(dev, wts, size, T, hp // 16, wp // 16) + rec["geometry"] = mk.geo.summary() + print("RUN", rec["geometry"], flush=True) + mk.run(patches) + ttnn.synchronize_device(dev) + except Exception as e: # noqa: BLE001 (L1 budget / DRAM OOM: record and stop) + rec.update(fits=False, error=f"{type(e).__name__}: {str(e)[:300]}") + raise + rec["fits"] = True + rec["first_run_s"] = time.perf_counter() - t0 + rec["mk_dram_mb"] = mem_mb(dev, "dram") - d1 + raw = [ttnn.to_torch(t).clone() for t in mk.taps] + rec["finite"] = all(bool(torch.isfinite(r.float()).all()) for r in raw) + tr0 = mem_mb(dev, "trace") + tid = ttnn.begin_trace_capture(dev, cq_id=0) + mk.run(patches) + ttnn.end_trace_capture(dev, tid, cq_id=0) + rec["mk_trace_kb"] = 1024 * (mem_mb(dev, "trace") - tr0) + ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) + t0 = time.perf_counter() + for _ in range(args.reps): + ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) + ttnn.synchronize_device(dev) + rec["mk_enc_ms"] = 1e3 * (time.perf_counter() - t0) / args.reps + rec["replays_bitexact"] = all(torch.equal(a, ttnn.to_torch(t)) for a, t in zip(raw, mk.taps)) + ttnn.release_trace(dev, tid) + if "ttnn_enc_ms" in rec: + rec["speedup"] = rec["ttnn_enc_ms"] / rec["mk_enc_ms"] + print(json.dumps(rec), flush=True) + if not args.no_ttnn: + from tt_depthpro2.tt import ttnn_enc + + t0 = time.perf_counter() + eng = ttnn_enc.Engine(dev, w, StageShape(T, hp, wp), size=size) + out = eng.run(patches) + ttnn.synchronize_device(dev) + rec["ttnn_eager_s"] = time.perf_counter() - t0 + N, Np = mk.geo.N, mk.geo.Np + cmp = [] + for a, b in zip(raw, out): + a = a.float().reshape(T, Np, -1)[:, :N] + b = ttnn.to_torch(b).float().reshape(T, Np, -1)[:, :N] + cmp.append({"pcc": H.pcc(a, b), "rel": H.rel_err(a, b)}) + rec["taps_mk_vs_ttnn"] = cmp + rec["ok_vs_ttnn"] = all(c["pcc"] >= 0.999 for c in cmp) + if "ttnn_enc_ms" not in rec: # no baseline bench entry (e.g. 640x480): time the ttnn engine traced here + tr0 = mem_mb(dev, "trace") + tid = ttnn.begin_trace_capture(dev, cq_id=0) + eng.run(patches) + ttnn.end_trace_capture(dev, tid, cq_id=0) + rec["ttnn_enc_trace_mb"] = mem_mb(dev, "trace") - tr0 + ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) + t0 = time.perf_counter() + for _ in range(args.reps): + ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) + ttnn.synchronize_device(dev) + rec["ttnn_enc_ms"] = 1e3 * (time.perf_counter() - t0) / args.reps + rec["ttnn_enc_ms_source"] = "measured here (traced)" + rec["speedup"] = rec["ttnn_enc_ms"] / rec["mk_enc_ms"] + ttnn.release_trace(dev, tid) + except Exception: # noqa: BLE001 + traceback.print_exc() + rec.setdefault("error", traceback.format_exc().splitlines()[-1][:300]) + finally: + rec["time"] = time.strftime("%Y-%m-%d %H:%M:%S") + print("REC " + json.dumps(rec), flush=True) + with open(LOG, "a") as f: + f.write(json.dumps(rec) + "\n") + gc.collect() + ttnn.close_device(dev) + + +if __name__ == "__main__": + main() diff --git a/code/tt_depthpro2/tests/mk_enc_vf.py b/code/tt_depthpro2/tests/mk_enc_vf.py new file mode 100644 index 0000000000000000000000000000000000000000..37d075dd146c476ffcf0b901c8534ecdb79a7b3a --- /dev/null +++ b/code/tt_depthpro2/tests/mk_enc_vf.py @@ -0,0 +1,93 @@ +# SPDX-License-Identifier: Apache-2.0 +"""ENC megakernel runtime valid-frame count (BASELINE.md 9.2 gate): a T-frame program with ``set_valid_frames(n)`` vs +the exact n-frame program on the same frames (PCC / max rel of the taps of frames < n), n = T bit-identical to the +default run before and after, and a trace replay after ``set_valid_frames`` equal to the eager run. + + bin/devrun -t 1800 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_vf.py --size S +""" + +from __future__ import annotations + +import argparse +import os +import 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: E402 +from tt_depthpro2.tests import mk_enc_ref as H # noqa: E402 +from tt_depthpro2.tt.mk_enc import arena as A # noqa: E402 +from tt_depthpro2.tt.mk_enc.program import MkEnc, MkEncWeights # noqa: E402 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--size", default="S") + ap.add_argument("--case", default="clip4_240x320") + args = ap.parse_args() + import ttnn + + g = H.load_case(args.case, args.size) + x = R.pad_to_multiple(g["x_norm"].float()) + T, _, hp, wp = x.shape + dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), + trace_region_size=8 << 20) + ok = True + try: + wts = MkEncWeights(dev, H.load_weights(args.size), args.size, "depth") + + def pt(frames: torch.Tensor): + return A.patchify(frames).to(torch.bfloat16).reshape(1, 1, -1, 768) + + def dev_patches(frames): + return ttnn.from_torch(pt(frames), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev, + memory_config=ttnn.DRAM_MEMORY_CONFIG) + + def taps(mk): + return [ttnn.to_torch(t).float().reshape(mk.geo.T, mk.geo.Np, -1)[:, :mk.geo.N] for t in mk.taps] + + mk = MkEnc(dev, wts, args.size, T, hp // 16, wp // 16) + patches = dev_patches(x) + mk.run(patches) + full = [ttnn.to_torch(t).clone() for t in mk.taps] + for n in range(1, T): + xn = x.clone() + xn[n:] = 0 + pn = dev_patches(xn) + mk.set_valid_frames(n) + mk.run(pn) + got = taps(mk) + ex = MkEnc(dev, wts, args.size, n, hp // 16, wp // 16) + ex.run(dev_patches(x[:n])) + want = taps(ex) + for i in range(4): + a, b = got[i][:n], want[i] + p, e = H.pcc(a, b), ((a - b).abs().max() / b.abs().max()).item() + ok = ok and p >= 0.9999 + print(f"n={n} tap{i}: T={T} program vs exact T={n}: pcc {p:.7f} max rel {e:.2e}", flush=True) + # trace replay after set_valid_frames == eager + eager = [ttnn.to_torch(t).clone() for t in mk.taps] + mk.set_valid_frames(T) + tid = ttnn.begin_trace_capture(dev, cq_id=0) + mk.run(pn) + ttnn.end_trace_capture(dev, tid, cq_id=0) + mk.set_valid_frames(n) + ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) + same = all(torch.equal(a, ttnn.to_torch(t)) for a, t in zip(eager, mk.taps)) + ttnn.release_trace(dev, tid) + ok = ok and same + print(f"n={n}: trace (captured at n={T}) replayed after set_valid_frames({n}) == eager: {same}", flush=True) + mk.set_valid_frames(T) + mk.run(patches) + same = all(torch.equal(a, ttnn.to_torch(t)) for a, t in zip(full, mk.taps)) + ok = ok and same + print(f"n=T={T} after the n < T runs bit-identical to the first run: {same}", flush=True) + finally: + ttnn.close_device(dev) + print("VF PASS" if ok else "VF FAIL", flush=True) + + +if __name__ == "__main__": + main() diff --git a/code/tt_depthpro2/tests/mk_enc_vf_e2e.py b/code/tt_depthpro2/tests/mk_enc_vf_e2e.py new file mode 100644 index 0000000000000000000000000000000000000000..29ef4dc31a0f2250f306dba7bc8540065707de6e --- /dev/null +++ b/code/tt_depthpro2/tests/mk_enc_vf_e2e.py @@ -0,0 +1,64 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Runtime valid-frame count through DepthPro2Device(engine="enc=mk"): one T = max_frames program per bucket serves +every n <= T clip (n frames of clip4_240x320 vs the float32 reference of the same n-frame clip), and the model +compiles only T in {max_frames, 1}. + + bin/devrun -t 1800 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_vf_e2e.py --size S +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys + +import torch + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) + +from tt_depthpro2.reference import model as ref # noqa: E402 +from tt_depthpro2.tests import baseline_helpers as BH # noqa: E402 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--size", default="S") + ap.add_argument("--case", default="clip4_240x320") + args = ap.parse_args() + import ttnn + from tt_depthpro2.tt.model import DepthPro2Device, planned_frames + + g, _ = BH.load_golden(args.case, args.size) + x = g["x_norm"].float() + T, _, h, w = x.shape + wts = ref.load_safetensors(os.path.join(BH.size_dir(args.size), "model.safetensors")) + cpu = ref.DepthPro2Reference(args.size, wts) + dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), + l1_small_size=BH.L1_SMALL_SIZE, trace_region_size=BH.TRACE_REGION_SIZE) + ok = True + try: + xp = ref.pad_to_multiple(x) + m = DepthPro2Device(dev, args.size, wts, None, buckets=[tuple(xp.shape[-2:])], max_frames=T, frames=(1,), + engine="enc=mk") + print("planned T:", planned_frames(T, (1,), clip_lengths="all", engine="enc=mk"), "compiled:", m.configurations()["depth"], + flush=True) + for n in range(1, T + 1): + inv = m.inverse_depth(xp[:n])[:, :h, :w] + with torch.no_grad(): + r = cpu.inverse_depth(x[:n]) + met = BH.drift_metrics(inv, r) + good = met["pcc"] >= 0.999 and met["absrel_valid"] <= 0.01 + ok = ok and good + print(json.dumps({"size": args.size, "case": args.case, "n": n, "T_program": T if n > 1 else 1, + "pcc_vs_fp32_ref": met["pcc"], "absrel_vs_fp32_ref": met["absrel_valid"], + "passed": good}), flush=True) + print("compiled after the n = 1..T calls:", m.configurations()["depth"], flush=True) + m.close() + finally: + ttnn.close_device(dev) + print("VF E2E PASS" if ok else "VF E2E FAIL", flush=True) + + +if __name__ == "__main__": + main() diff --git a/code/tt_depthpro2/tests/mk_enc_xcheck.py b/code/tt_depthpro2/tests/mk_enc_xcheck.py new file mode 100644 index 0000000000000000000000000000000000000000..cd6c691f853b5e5a1704698a15d89aeba449dca0 --- /dev/null +++ b/code/tt_depthpro2/tests/mk_enc_xcheck.py @@ -0,0 +1,113 @@ +# SPDX-License-Identifier: Apache-2.0 +"""ENC megakernel vs the ttnn baseline engine (tt/ttnn_enc.py) on the device, for shapes whose CPU reference is too +slow: same patches, taps compared (PCC / rel err), both engines timed under trace (device time per run). + + bin/devrun -t 3600 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_xcheck.py --size L \ + --case img_vga --resize 736 1280 --tframes 16 [--no-ttnn] +""" + +from __future__ import annotations + +import argparse +import os +import sys +import time + +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: E402 +from tt_depthpro2.tests import mk_enc_ref as H # noqa: E402 +from tt_depthpro2.tt import StageShape # noqa: E402 +from tt_depthpro2.tt.mk_enc import arena as A # noqa: E402 +from tt_depthpro2.tt.mk_enc.program import MkEnc # noqa: E402 + + +def trace_time(dev, fn, reps): + import ttnn + + fn() + ttnn.synchronize_device(dev) + tid = ttnn.begin_trace_capture(dev, cq_id=0) + out = fn() + ttnn.end_trace_capture(dev, tid, cq_id=0) + ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) + t0 = time.perf_counter() + for _ in range(reps): + ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) + ttnn.synchronize_device(dev) + dt = (time.perf_counter() - t0) / reps + ttnn.release_trace(dev, tid) + return out, dt + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--size", default="L") + ap.add_argument("--case", default="img_vga") + ap.add_argument("--resize", type=int, nargs=2, default=None) + ap.add_argument("--tframes", type=int, default=0) + ap.add_argument("--reps", type=int, default=3) + ap.add_argument("--no-ttnn", action="store_true") + ap.add_argument("--determinism", type=int, default=0, help="extra trace replays compared bitwise") + ap.add_argument("--save", default=None, help="torch.save the mk (and ttnn) taps [T, N, C] to this path") + args = ap.parse_args() + import ttnn + + g = H.load_case(args.case, args.size) + x = R.pad_to_multiple(g["x_norm"].float()) + if args.resize: + x = torch.nn.functional.interpolate(x, size=tuple(args.resize), mode="bilinear", align_corners=False) + if args.tframes: + gen = torch.Generator().manual_seed(0) + x = x.repeat(-(-args.tframes // x.shape[0]), 1, 1, 1)[:args.tframes] + x = x + 0.1 * torch.randn(x.shape, generator=gen) + T, _, hp, wp = x.shape + w = H.load_weights(args.size) + dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), + trace_region_size=16 << 20) + try: + pt = A.patchify(x).to(torch.bfloat16).reshape(1, 1, -1, 768) + patches = ttnn.from_torch(pt, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev, + memory_config=ttnn.DRAM_MEMORY_CONFIG) + t0 = time.perf_counter() + mk = MkEnc(dev, w, args.size, T, hp // 16, wp // 16) + print(mk.geo.summary(), f"init {time.perf_counter() - t0:.1f} s", flush=True) + taps_mk, dt_mk = trace_time(dev, lambda: mk.run(patches), args.reps) + print(f"MK {args.size} T={T} {hp}x{wp}: {1e3 * dt_mk:.2f} ms / run", flush=True) + dmk = [ttnn.to_torch(t).float().reshape(T, mk.geo.Np, -1)[:, :mk.geo.N] for t in taps_mk] + bad = [int((~torch.isfinite(d)).sum()) for d in dmk] + print(f"MK non-finite tap values: {bad}", flush=True) + if args.determinism: + raw = [ttnn.to_torch(t).clone() for t in taps_mk] + tid = ttnn.begin_trace_capture(dev, cq_id=0) + mk.run(patches) + ttnn.end_trace_capture(dev, tid, cq_id=0) + mism = 0 + for _ in range(args.determinism): + ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) + mism += sum(int(not torch.equal(a, ttnn.to_torch(t))) for a, t in zip(raw, mk.taps)) + ttnn.release_trace(dev, tid) + print(f"MK determinism: {args.determinism} replays, {mism} mismatching taps", flush=True) + if not args.no_ttnn: + from tt_depthpro2.tt import ttnn_enc + + eng = ttnn_enc.Engine(dev, w, StageShape(T, hp, wp), size=args.size) + taps_tt, dt_tt = trace_time(dev, lambda: eng.run(patches), args.reps) + print(f"TTNN {args.size} T={T} {hp}x{wp}: {1e3 * dt_tt:.2f} ms / run", flush=True) + dtt = [ttnn.to_torch(t).float().reshape(T, mk.geo.Np, -1)[:, :mk.geo.N] for t in taps_tt] + for i, (a, b) in enumerate(zip(dmk, dtt)): + print(f" tap{i} mk vs ttnn: pcc {H.pcc(a, b):.6f} rel {H.rel_err(a, b):.3e}", flush=True) + if f"tap{i}" in g and not (args.resize or args.tframes): + r = g[f"tap{i}"].float() + print(f" tap{i} vs golden: mk pcc {H.pcc(a, r):.6f} rel {H.rel_err(a, r):.3e} | ttnn pcc " + f"{H.pcc(b, r):.6f} rel {H.rel_err(b, r):.3e}", flush=True) + if args.save: + torch.save({"mk": dmk, "ttnn": dtt if not args.no_ttnn else None}, args.save) + finally: + ttnn.close_device(dev) + + +if __name__ == "__main__": + main() diff --git a/code/tt_depthpro2/tests/mk_fov_check.py b/code/tt_depthpro2/tests/mk_fov_check.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f49fcac82868d736f605ee36d75c978f725aad --- /dev/null +++ b/code/tt_depthpro2/tests/mk_fov_check.py @@ -0,0 +1,133 @@ +# SPDX-License-Identifier: Apache-2.0 +"""FOV stage megakernel engine (tt/mk_fov) vs the goldens (SPEC §5 FOV gate: f_px within max(1 %, 2 x official bf16 +drift)) and vs the ttnn FOV engine on the same fpatches (logits, traced device time); n <= T frames on a T program. + + bin/devrun -t 1800 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_fov_check.py +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import time + +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: E402 +from tt_depthpro2.tests import baseline_helpers as BH # noqa: E402 +from tt_depthpro2.tests import mk_enc_ref as H # noqa: E402 +from tt_depthpro2.tt import StageShape # noqa: E402 +from tt_depthpro2.tt.mk_enc import arena as A # noqa: E402 + +CASES = ("img_vga", "img_384x512", "clip4_240x320", "img_375x500_pad") +LOG = "/home/ubuntu/experiments/tt-models/logs/depthpro2/mk_enc/fov.jsonl" + + +def trace_ms(dev, fn, reps=5): + import ttnn + + fn() + ttnn.synchronize_device(dev) + tid = ttnn.begin_trace_capture(dev, cq_id=0) + out = fn() + ttnn.end_trace_capture(dev, tid, cq_id=0) + ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) + res = ttnn.to_torch(out).float().clone() + t0 = time.perf_counter() + for _ in range(reps): + ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) + ttnn.synchronize_device(dev) + ms = 1e3 * (time.perf_counter() - t0) / reps + same = torch.equal(res, ttnn.to_torch(out).float()) + ttnn.release_trace(dev, tid) + return res, ms, same + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cases", default=",".join(CASES)) + ap.add_argument("--no-ttnn", action="store_true") + ap.add_argument("--bench-t4", action="store_true", help="also time VGA T=4 (mk and ttnn)") + args = ap.parse_args() + import ttnn + from tt_depthpro2.tt import mk_fov, ttnn_fov + + dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), + l1_small_size=BH.L1_SMALL_SIZE, trace_region_size=64 << 20) + fw = R.load_safetensors(os.path.join(BH.fov_dir(), "model.safetensors")) + ok = True + try: + wm = mk_fov.Engine.prepare_weights(dev, fw) + wt = None if args.no_ttnn else ttnn_fov.Engine.prepare_weights(dev, fw) + + def dev_in(y): + np_ = -(-(y.shape[-2] // 16) * (y.shape[-1] // 16) // 32) * 32 + p = A.patchify(y).to(torch.bfloat16).reshape(1, 1, -1, 768) + assert p.shape[-2] == y.shape[0] * np_ + return ttnn.from_torch(p, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev, + memory_config=ttnn.DRAM_MEMORY_CONFIG) + + for case in args.cases.split(","): + g, _ = BH.load_golden(case, "S") + x = g["x_norm"].float() + T, _, h, w = x.shape + y = R.fov_resize(x) + shape = StageShape(T, y.shape[-2], y.shape[-1]) + fp = dev_in(y) + em = mk_fov.Engine(dev, wm, shape) + lm, ms_m, same_m = trace_ms(dev, lambda: em.run(fp)) + lm = lm.reshape(T, 2) + deg = R.fov_logits_to_deg(lm, (h, w), tuple(y.shape[-2:])) + f = float(R.median_focal_length_px(deg, h, w)) + fg = float(g["focallength_px"]) + f_rel = abs(f / fg - 1) + budget, why = BH.fov_budget(case) + rec = {"case": case, "T": T, "fov_hw": list(y.shape[-2:]), "engine": "mk", "f_px": f, "f_px_golden": fg, + "f_rel": f_rel, "f_budget": budget, "budget_from": why, + "fov_deg_maxabs": float((deg - g["fov_deg"].reshape(deg.shape)).abs().max()), + "fov_ms": ms_m, "replay_bitexact": same_m, "passed": f_rel <= budget and same_m} + if wt is not None: + et = ttnn_fov.Engine(dev, wt, shape) + lt, ms_t, _ = trace_ms(dev, lambda: et.run(fp)) + lt = lt.reshape(T, 2) + degt = R.fov_logits_to_deg(lt, (h, w), tuple(y.shape[-2:])) + ft = float(R.median_focal_length_px(degt, h, w)) + rec.update(ttnn_f_rel=abs(ft / fg - 1), ttnn_fov_ms=ms_t, + logits_maxabs_mk_vs_ttnn=float((lm - lt).abs().max())) + del et + # n < T frames on this T program (frames independent): zero frames in the unused slots + if T > 1: + y2 = y.clone() + y2[2:] = 0 + l2 = ttnn.to_torch(em.run(dev_in(y2))).float().reshape(T, 2)[:2] + rec["n2_of_T_maxabs_vs_full"] = float((l2 - lm[:2]).abs().max()) + ok = ok and rec["passed"] + rec["time"] = time.strftime("%Y-%m-%d %H:%M:%S") + print(json.dumps(rec), flush=True) + with open(LOG, "a") as fh: + fh.write(json.dumps(rec) + "\n") + del em, fp + if args.bench_t4: + g, _ = BH.load_golden("img_vga", "S") + y = R.fov_resize(g["x_norm"].float()).repeat(4, 1, 1, 1) + shape = StageShape(4, y.shape[-2], y.shape[-1]) + fp = dev_in(y) + em = mk_fov.Engine(dev, wm, shape) + _, ms_m, same_m = trace_ms(dev, lambda: em.run(fp)) + rec = {"case": "img_vga x4", "T": 4, "fov_hw": list(y.shape[-2:]), "fov_ms": ms_m, "replay_bitexact": same_m} + if wt is not None: + et = ttnn_fov.Engine(dev, wt, shape) + _, ms_t, _ = trace_ms(dev, lambda: et.run(fp)) + rec["ttnn_fov_ms"] = ms_t + print(json.dumps(rec), flush=True) + finally: + ttnn.close_device(dev) + print("FOV PASS" if ok else "FOV FAIL", flush=True) + + +if __name__ == "__main__": + main() diff --git a/code/tt_depthpro2/tests/test_device_baseline.py b/code/tt_depthpro2/tests/test_device_baseline.py new file mode 100644 index 0000000000000000000000000000000000000000..3004eae7414b6efa277427c854fc9c9a8eb5eeb8 --- /dev/null +++ b/code/tt_depthpro2/tests/test_device_baseline.py @@ -0,0 +1,382 @@ +# SPDX-License-Identifier: Apache-2.0 +"""ttnn baseline of DepthPro2 on the device: stage-level PCC (ENC / DEC / FOV, S) and end-to-end gates (SPEC §5) +for every size through ``DepthPro2Device`` (traced), plus trace-replay determinism. + +Run through the workspace lock, naming this file: +``bin/devrun -t 5400 -- python -m pytest -q -s -o faulthandler_timeout=3000 \ + bundles/depthpro2/code/tt_depthpro2/tests/test_device_baseline.py`` +(``-k "stage"`` / ``-k "e2e and S"`` select subsets). Results are appended to +``logs/depthpro2/baseline/results.jsonl`` (``DEPTHPRO2_BASELINE_RESULTS`` overrides). +""" + +from __future__ import annotations + +import json +import os +import sys +import time + +import pytest +import torch + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import baseline_helpers as H # noqa: E402 + +from tt_depthpro2.reference import model as ref # noqa: E402 +from tt_depthpro2.tt import StageShape # noqa: E402 +from tt_depthpro2.tt.weights import load_weights, unfold_patches # noqa: E402 + +pytestmark = pytest.mark.device + +RESULTS = os.environ.get("DEPTHPRO2_BASELINE_RESULTS", os.path.join(H.ROOT, "logs/depthpro2/baseline/results.jsonl")) +E2E_CASES = ("img_vga", "clip4_240x320", "img_375x500_pad") + + +def record(kind: str, **kw) -> None: + kw = {"kind": kind, "time": time.strftime("%Y-%m-%d %H:%M:%S"), **kw} + os.makedirs(os.path.dirname(RESULTS), exist_ok=True) + with open(RESULTS, "a") as f: + f.write(json.dumps(kw) + "\n") + print(json.dumps(kw)) + + +_W = {} + + +def weights(name: str): + if name not in _W: + _W[name] = load_weights(H.fov_dir() if name == "fov" else H.size_dir(name)) + return _W[name] + + +def to_dev(t: torch.Tensor, device): + import ttnn + + return ttnn.from_torch(t.to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device, + memory_config=ttnn.DRAM_MEMORY_CONFIG) + + +# ----------------------------------------------------------------------------------------------- stage level (S) + + +@pytest.mark.parametrize("case", ["img_384x512", "clip4_240x320"]) +def test_enc_stage(device, case): + import ttnn + + from tt_depthpro2.tt import ttnn_enc + + g, _ = H.load_golden(case, "S") + x = ref.pad_to_multiple(g["x_norm"]) + t, _, hp, wp = x.shape + shape = StageShape(t, hp, wp) + eng = ttnn_enc.Engine(device, ttnn_enc.Engine.prepare_weights(device, weights("S"), "S"), shape) + blocks = {} + eng.trunk.hook = lambda i, xt: blocks.__setitem__(i, ttnn.to_torch(xt).float()) + taps = eng.run(to_dev(unfold_patches(x, shape.np_).reshape(1, 1, -1, 768), device)) + n = shape.n + blk = [] + for i, xb in sorted(blocks.items()): + dev_b = torch.cat([xb[:, 0, n:n + 5], xb[:, 0, :n]], dim=1) + blk.append(round(H.pcc(dev_b, g[f"enc.block{i:02d}.out"]), 6)) + res = [] + for i, tp in enumerate(taps): + d = ttnn.to_torch(tp).float().reshape(t, shape.np_, -1)[:, :n] + res.append({"pcc": H.pcc(d, g[f"tap{i}"]), "max_rel": H.max_rel(d, g[f"tap{i}"])}) + record("stage_enc", size="S", case=case, taps=res, block_pcc=blk) + assert min(r["pcc"] for r in res) >= 0.999, res + assert min(blk) >= 0.999, blk + + +@pytest.mark.parametrize("case", ["img_384x512", "clip4_240x320", "img_vga"]) +def test_dec_stage(device, case): + import ttnn + + from tt_depthpro2.tt import ttnn_dec + + g, _ = H.load_golden(case, "S") + x = ref.pad_to_multiple(g["x_norm"]) + t, _, hp, wp = x.shape + shape = StageShape(t, hp, wp) + eng = ttnn_dec.Engine(device, ttnn_dec.Engine.prepare_weights(device, weights("S"), "S"), shape) + taps = [] + for i in range(4): + tp = torch.zeros(t, shape.np_, g[f"tap{i}"].shape[-1]) + tp[:, :shape.n] = g[f"tap{i}"] + taps.append(to_dev(tp.reshape(1, 1, -1, tp.shape[-1]), device)) + out = ttnn.to_torch(eng.run(taps)).float().reshape(t, hp, wp) + ref_o = g["head.out"][:, 0] + r = {"pcc": H.pcc(out, ref_o), "max_rel": H.max_rel(out, ref_o)} + record("stage_dec", size="S", case=case, inv=r) + assert r["pcc"] >= 0.9999, r + + +@pytest.mark.parametrize("case", ["img_384x512", "clip4_240x320", "img_375x500_pad"]) +def test_fov_stage(device, case): + import ttnn + + from tt_depthpro2.tt import ttnn_fov + + g, _ = H.load_golden(case, "S") + x = g["x_norm"] + y = ref.fov_resize(x) + t, _, h, w = y.shape + shape = StageShape(t, h, w) + fw = weights("fov") + with torch.no_grad(): + tok, grid = ref.fov_trunk(y, fw) + lg_ref = ref.fov_head(tok, grid, fw) + eng = ttnn_fov.Engine(device, ttnn_fov.Engine.prepare_weights(device, fw), shape) + lg = ttnn.to_torch(eng.run(to_dev(unfold_patches(y, shape.np_).reshape(1, 1, -1, 768), device))).float().reshape(t, 2) + deg = ref.fov_logits_to_deg(lg, tuple(x.shape[-2:]), (h, w)) + f = float(ref.median_focal_length_px(deg, *x.shape[-2:])) + f_ref = float(g["focallength_px"]) + r = {"logit_maxabs": float((lg - lg_ref).abs().max()), "fov_deg_maxabs": float((deg - g["fov_deg"]).abs().max()), + "f_px": f, "f_px_golden": f_ref, "f_rel": abs(f / f_ref - 1)} + fbud, fwhy = H.fov_budget(case) + r.update(f_rel_budget=fbud, f_budget_from=fwhy) + record("stage_fov", case=case, fov=r) + assert r["f_rel"] <= fbud, r + + +# ----------------------------------------------------------------------------------------------- end to end + + +def _cases(size: str): + return [c for c in E2E_CASES if H.golden_path(c, size) is not None] + + +@pytest.mark.parametrize("size", ["S", "B", "L", "H"]) +def test_e2e(device, size): + """DepthPro2Device (traced ENC + DEC, traced FOV) on every golden case of ``size``; SPEC §5 gates.""" + from tt_depthpro2.tt.model import DepthPro2Device + + cases = _cases(size) + goldens = {c: H.load_golden(c, size)[0] for c in cases} + shapes = {c: ref.pad_to_multiple(g["x_norm"]).shape for c, g in goldens.items()} + buckets = sorted({(s[-2], s[-1]) for s in shapes.values()}) + fov_shapes = sorted({tuple(ref.fov_resize(g["x_norm"][:1]).shape[-2:]) for g in goldens.values()}) + t0 = time.perf_counter() + # T=1 everywhere up front; the clip (T=4) compiles on first use (exercises the release / recapture path) + m = DepthPro2Device(device, size, weights(size), weights("fov"), buckets=buckets, max_frames=1, fov_shapes=fov_shapes) + build_s = time.perf_counter() - t0 + failures = [] + try: + for c in cases: + g = goldens[c] + x = g["x_norm"] + t, _, h, w = x.shape + t1 = time.perf_counter() + inv = m.inverse_depth(ref.pad_to_multiple(x))[:, :h, :w] + first_ms = (time.perf_counter() - t1) * 1e3 + t1 = time.perf_counter() + inv2 = m.inverse_depth(ref.pad_to_multiple(x))[:, :h, :w] + call_ms = (time.perf_counter() - t1) * 1e3 + met = H.drift_metrics(inv, g["inverse_depth"].reshape(t, h, w)) + budget, why = H.absrel_budget(c, size) + y = ref.fov_resize(x) + lg = m.fov_logits(y) + deg = ref.fov_logits_to_deg(lg, (h, w), tuple(y.shape[-2:])) + f = float(ref.median_focal_length_px(deg, h, w)) + f_rel = abs(f / float(g["focallength_px"]) - 1) + fbud, fwhy = H.fov_budget(c) + ok = met["pcc"] >= 0.999 and met["absrel_valid"] <= budget and f_rel <= fbud and torch.equal(inv, inv2) + record("e2e", size=size, case=c, golden=os.path.basename(os.path.dirname(H.golden_path(c, size))), metrics=met, absrel_budget=budget, budget_from=why, f_px=f, + f_px_golden=float(g["focallength_px"]), f_rel=f_rel, f_rel_budget=fbud, f_budget_from=fwhy, fov_deg_maxabs=float((deg - g["fov_deg"]).abs().max()), + repeat_bitexact=bool(torch.equal(inv, inv2)), first_call_ms=first_ms, call_ms=call_ms, build_s=build_s, + passed=ok) + if not ok: + failures.append(c) + finally: + m.close() + assert not failures, failures + + +def test_trace_determinism(device): + """50 back-to-back replays of one traced configuration are bit-identical (the 500-run stress is in the bench).""" + from tt_depthpro2.tt.model import DepthPro2Device + + g, _ = H.load_golden("img_vga", "S") + x = ref.pad_to_multiple(g["x_norm"]) + m = DepthPro2Device(device, "S", weights("S"), None, buckets=[tuple(x.shape[-2:])], max_frames=1) + try: + first = m.inverse_depth(x) + diffs = sum(int(not torch.equal(first, m.inverse_depth(x))) for _ in range(50)) + finally: + m.close() + record("determinism", size="S", case="img_vga", replays=50, mismatches=diffs) + assert diffs == 0 + + +@pytest.mark.parametrize("n", [2, 3]) +def test_valid_frames(device, n): + """One T=4 program serving an n-frame clip (runtime valid-frame count) == the exact T=n program.""" + import ttnn + + from tt_depthpro2.tt import ttnn_dec, ttnn_enc + + g, _ = H.load_golden("clip4_240x320", "S") + x = ref.pad_to_multiple(g["x_norm"])[:n] + we = ttnn_enc.Engine.prepare_weights(device, weights("S"), "S") + wd = ttnn_dec.Engine.prepare_weights(device, weights("S"), "S") + + def run(t): + sh = StageShape(t, 256, 320) + enc, dec = ttnn_enc.Engine(device, we, sh), ttnn_dec.Engine(device, wd, sh) + xp = torch.cat([x, x.new_zeros(t - n, 3, 256, 320)]) if t > n else x + enc.set_valid_frames(n) + return ttnn.to_torch(dec.run(enc.run(to_dev(unfold_patches(xp, sh.np_).reshape(1, 1, -1, 768), device)))).float()[:n] + + exact, padded = run(n), run(4) + r = {"pcc": H.pcc(padded, exact), "max_rel": H.max_rel(padded, exact)} + record("valid_frames", size="S", case="clip4_240x320", n=n, program_T=4, vs_exact=r) + assert r["pcc"] >= 0.99999, r + + +def test_fov_any_t(device): + """fov_logits on 1 frame and on the window (4) with the programs T in {1, 4}; 3 frames run in the T=4 program.""" + from tt_depthpro2.tt.model import DepthPro2Device + + g, _ = H.load_golden("clip4_240x320", "S") + y = ref.fov_resize(g["x_norm"]) + fw = weights("fov") + with torch.no_grad(): + lg_ref = ref.fov_head(*ref.fov_trunk(y, fw), fw) + m = DepthPro2Device(device, "S", weights("S"), fw, buckets=[(256, 320)], max_frames=4, frames=(1,)) + try: + res = {t: float((m.fov_logits(y[:t]) - lg_ref[:t]).abs().max()) for t in (1, 3, 4)} + finally: + m.close() + record("fov_any_t", case="clip4_240x320", logit_maxabs=res) + assert max(res.values()) < 0.02, res + + +def test_kv_stream(device): + """Unbuffered video (KV cache, window 4) through tt_depthpro2.streaming on stream_unbuf_w4_n6 (S): per frame + PCC >= 0.999 and AbsRel <= max(2 x official clip4 drift, 0.01); a 2nd interleaved stream is bit-identical.""" + from tt_depthpro2.streaming import DepthStream + from tt_depthpro2.tt.model import DepthPro2Device + + g, _ = H.load_golden("stream_unbuf_w4_n6", "S") + frames = ref.preprocess(g["input_u8"].round().to(torch.uint8).numpy()) + m = DepthPro2Device(device, "S", weights("S"), None, buckets=[(256, 320)], max_frames=4, frames=(1,), kv_cache=True, + kv_streams=2) + times = [] + + def step(clip, cache): + t0 = time.perf_counter() + out = m.inverse_depth_step(ref.pad_to_multiple(clip), cache)[:, :240, :320] + times.append((time.perf_counter() - t0) * 1e3) + return out + + def run_stream(): + st = DepthStream(lambda c: None, window=4, overlap=0, f_px=float(g["focallength_px"]), mode="unbuffered", + predict_step=step, open_cache=lambda: m.kv_cache((256, 320), 4)) + return st + + try: + a, b = run_stream(), run_stream() # two open caches, steps interleaved + pa, pb = [], [] + for f in frames: + pa += a.step(f) + pb += b.step(f) + pa += a.flush() + pb += b.flush() + a.close() + b.close() + nbytes = m.kv_cache_bytes() + finally: + m.close() + d, src = H.official_drift_absrel("clip4_240x320", "S") + budget = max(2 * (d or 0.0), 0.01) + per = [] + for p in pa: + met = H.drift_metrics(p.inverse_depth, g["inverse_depth"][p.index]) + per.append({"frame": p.index, "pcc": met["pcc"], "absrel_valid": met["absrel_valid"]}) + same = all(torch.equal(x.inverse_depth, y.inverse_depth) for x, y in zip(pa, pb)) + record("kv_stream", size="S", case="stream_unbuf_w4_n6", window=4, frames=per, absrel_budget=budget, + budget_from=src, interleaved_bitexact=same, cache_bytes=nbytes, step_ms=times) + assert len(per) == len(frames) and same + assert all(r["pcc"] >= 0.999 and r["absrel_valid"] <= budget for r in per), per + + +@pytest.mark.parametrize("size", ["S", "B", "L", "H"]) +def test_vga_t16(device, size): + """Regression (round 3): a 16-frame 480x640 clip on the T=16 program (n = 16) and its first 5 frames through + the valid-frame path (n = 5), against the float32 reference (tests/make_clip16_refs.py). Every frame: finite, + PCC >= 0.999.""" + from safetensors.torch import load_file + + from tt_depthpro2.tt.model import DepthPro2Device + + path = os.path.join(H.BASELINE_REF, f"clip16_480x640__{size}.safetensors") + if not os.path.exists(path): + pytest.skip(f"{path} missing (tests/make_clip16_refs.py)") + r = load_file(path) + x = r["x_norm"] + m = DepthPro2Device(device, size, weights(size), None, buckets=[(480, 640)], max_frames=16) + res = {} + try: + for n, key in ((16, "inverse_depth"), (5, "inverse_depth_n5")): + inv = m.inverse_depth(x[:n]) + ref_inv = r[key] + per = [H.pcc(inv[f], ref_inv[f]) for f in range(n)] + met = [H.drift_metrics(inv[f], ref_inv[f]) for f in range(n)] + # AbsRel (depth) is not gated: a few valid pixels (ref >= 1% of the max) at the seams of the rolled frames + # come out 0 after the final ReLU, and 1 / 1e-9 dominates the mean; the inverse-depth p99 is reported. + res[n] = {"finite": bool(torch.isfinite(inv).all()), "absmax": float(inv.abs().max()), "pcc_min": min(per), + "pcc_frames": [round(p, 6) for p in per], + "absrel_valid_median": float(torch.tensor([m["absrel_valid"] for m in met]).median()), + "inv_rel_p99_valid_max": max(m["inv_rel_p99_valid"] for m in met)} + finally: + m.close() + record("vga_t16", size=size, program_T=16, results=res) + for n, v in res.items(): + assert v["finite"] and v["pcc_min"] >= 0.999, (n, v) + + +@pytest.mark.parametrize("size", ["L", "H"]) +def test_startup_3buckets_kv(device, size): + """Regression (round 3): start-up with 3 buckets (480x640, 640x480, 256x320), window 16, images, FOV and the KV + cache (serve's DepthPro2 configuration), then one call per bucket and one KV step. Needs a trace region of + ``trace_region_bytes`` (run with DEPTHPRO2_TRACE_REGION set accordingly).""" + from tt_depthpro2.tt.model import DepthPro2Device, planned_frames, trace_region_bytes + + buckets = [(480, 640), (640, 480), (256, 320)] + need = trace_region_bytes(size, buckets, planned_frames(16, clip_lengths="all"), kv_cache=True) + have = int(os.environ.get("DEPTHPRO2_TRACE_REGION", "0") or 0) + if have < need: + pytest.skip(f"needs DEPTHPRO2_TRACE_REGION >= {need} (trace_region_bytes), have {have}") + t0 = time.perf_counter() + m = DepthPro2Device(device, size, weights(size), weights("fov"), buckets=buckets, max_frames=16, frames=(1,), + clip_lengths="all", kv_cache=True) + build = time.perf_counter() - t0 + out = {} + try: + for hp, wp in buckets: + inv = m.inverse_depth(torch.randn(1, 3, hp, wp) * 0.5) + out[f"{hp}x{wp}"] = bool(torch.isfinite(inv).all()) + c = m.kv_cache((256, 320), 4) + st = m.inverse_depth_step(torch.randn(1, 3, 256, 320) * 0.5, c) + out["kv_step"] = bool(torch.isfinite(st).all()) + c.close() + finally: + m.close() + record("startup_3buckets_kv", size=size, build_s=build, finite=out, trace_region_estimate_mb=need >> 20) + assert all(out.values()), out + + +def test_engine_switch(): + from tt_depthpro2.tt import model as M + + assert M.parse_engine(None) == {"enc": "ttnn", "dec": "ttnn", "fov": "ttnn"} + assert M.parse_engine("enc=mk,dec=ttnn") == {"enc": "mk", "dec": "ttnn", "fov": "ttnn"} + assert M.parse_engine({"fov": "mk"})["fov"] == "mk" + with pytest.raises(ValueError): + M.parse_engine("enc=foo") + for stage in ("enc", "dec", "fov"): + assert M.engine_class(stage, "ttnn").__name__ == "Engine" + try: + cls = M.engine_class(stage, "mk") + assert hasattr(cls, "run") + except RuntimeError as e: # mk module absent / incomplete: a clear error naming the module + assert f"mk_{stage}" in str(e) diff --git a/code/tt_depthpro2/tests/test_device_mk_dec.py b/code/tt_depthpro2/tests/test_device_mk_dec.py new file mode 100644 index 0000000000000000000000000000000000000000..df41c48ca9070b7d51c83976e1dff6aee285da85 --- /dev/null +++ b/code/tt_depthpro2/tests/test_device_mk_dec.py @@ -0,0 +1,125 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Device tests of the DEC megakernel (``tt/mk_dec``): the stage on the golden taps vs the float32 golden +``head.out`` (SPEC section 5 stage gate: PCC >= 0.99999, max rel <= 1 %), the Engine contract (persistent-free output, +trace capture) and trace-replay determinism. + +Run through the device lock, naming this file explicitly: + + bin/devrun -t 3600 -- python -m pytest -x -q -s bundles/depthpro2/code/tt_depthpro2/tests/test_device_mk_dec.py \ + -o faulthandler_timeout=3000 [-k S] + +Records are appended to ``logs/depthpro2/mk_dec/results.jsonl``. +""" + +from __future__ import annotations + +import json +import os +import time + +import pytest +import torch + +from tt_depthpro2.reference import model as R +from tt_depthpro2.tests import baseline_helpers as BH +from tt_depthpro2.tt import StageShape + +ttnn = pytest.importorskip("ttnn") + +RESULTS = os.path.join(BH.ROOT, "logs/depthpro2/mk_dec/results.jsonl") +STAGE_PCC = float(os.environ.get("MK_DEC_STAGE_PCC", "0.99999")) +STAGE_REL = float(os.environ.get("MK_DEC_STAGE_REL", "0.01")) +DET_REPLAYS = int(os.environ.get("MK_DEC_DET_REPLAYS", "500")) + +CASES = [ + ("S", "img_384x512"), ("S", "img_vga"), ("S", "clip4_240x320"), ("S", "img_375x500_pad"), + ("B", "img_vga"), ("B", "clip4_240x320"), ("B", "img_375x500_pad"), + ("L", "img_vga"), ("L", "clip4_240x320"), + ("H", "img_vga"), ("H", "clip4_240x320"), +] + + +def record(kind: str, **kw) -> None: + kw = {"kind": kind, "time": time.strftime("%Y-%m-%d %H:%M:%S"), **kw} + os.makedirs(os.path.dirname(RESULTS), exist_ok=True) + with open(RESULTS, "a") as f: + f.write(json.dumps(kw) + "\n") + print(json.dumps(kw)) + + +@pytest.fixture(scope="module") +def device(): + dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), + l1_small_size=32768, trace_region_size=32 << 20) + yield dev + ttnn.close_device(dev) + + +_W = {} + + +def prepared(device, size: str): + from tt_depthpro2.tt import mk_dec + + if size not in _W: + _W.clear() + w = R.load_safetensors(os.path.join(BH.size_dir(size), "model.safetensors")) + _W[size] = mk_dec.Engine.prepare_weights(device, w, size) + return _W[size] + + +def golden_taps(device, g, shape: StageShape): + out = [] + for i in range(4): + t = g[f"tap{i}"].float() + z = torch.zeros(shape.frames, shape.np_, t.shape[-1]) + z[:, :t.shape[1]] = t + out.append(ttnn.from_torch(z.reshape(1, 1, -1, t.shape[-1]).to(torch.bfloat16), dtype=ttnn.bfloat16, + layout=ttnn.TILE_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG)) + return out + + +@pytest.mark.parametrize("size,case", CASES, ids=[f"{s}-{c}" for s, c in CASES]) +def test_stage(device, size, case): + from tt_depthpro2.tt import mk_dec + + g, _ = BH.load_golden(case, size) + x = R.pad_to_multiple(g["x_norm"]) + t, _, hp, wp = x.shape + shape = StageShape(t, hp, wp) + eng = mk_dec.Engine(device, prepared(device, size), shape) + taps = golden_taps(device, g, shape) + out = ttnn.to_torch(eng.run(taps)).float().reshape(t, hp, wp) + ref = g["head.out"][:, 0] + r = {"pcc": BH.pcc(out, ref), "max_rel": BH.max_rel(out, ref), "aborts": len(eng.mk.aborts())} + # cropped inverse depth (what the user sees) with the SPEC metrics + h, w = g["inverse_depth"].shape[-2:] + r["crop"] = BH.drift_metrics(out[:, :h, :w], g["inverse_depth"].reshape(t, h, w)) + record("stage_dec_mk", size=size, case=case, **r) + assert r["aborts"] == 0 + assert r["pcc"] >= STAGE_PCC and r["max_rel"] <= STAGE_REL, r + + +def test_trace_determinism(device): + """``DET_REPLAYS`` trace replays of the stage are bitwise identical (and equal to the eager run).""" + from tt_depthpro2.tt import mk_dec + + g, _ = BH.load_golden("img_vga", "S") + x = R.pad_to_multiple(g["x_norm"]) + t, _, hp, wp = x.shape + shape = StageShape(t, hp, wp) + eng = mk_dec.Engine(device, prepared(device, "S"), shape) + taps = golden_taps(device, g, shape) + first = ttnn.to_torch(eng.run(taps)).float() + tid = ttnn.begin_trace_capture(device, cq_id=0) + out = eng.run(taps) + ttnn.end_trace_capture(device, tid, cq_id=0) + bad = 0 + try: + for _ in range(DET_REPLAYS): + ttnn.execute_trace(device, tid, cq_id=0, blocking=False) + bad += int(not torch.equal(ttnn.to_torch(out).float(), first)) + finally: + ttnn.release_trace(device, tid) + record("determinism_mk_dec", size="S", case="img_vga", replays=DET_REPLAYS, mismatches=bad) + assert bad == 0 diff --git a/code/tt_depthpro2/tests/test_device_mk_enc.py b/code/tt_depthpro2/tests/test_device_mk_enc.py new file mode 100644 index 0000000000000000000000000000000000000000..f2d1300090079e602914d1916883185f655e9cb9 --- /dev/null +++ b/code/tt_depthpro2/tests/test_device_mk_enc.py @@ -0,0 +1,187 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Device tests of the ENC megakernel (``tt/mk_enc``): the 4 taps against the float32 goldens / reference, FOV-trunk +mode, determinism (repeated runs and trace replays bitwise identical), runtime valid-frame count (set_valid_frames). + +Run through the device lock, naming this file explicitly: + + bin/devrun -t 1800 -- python -m pytest -x -q bundles/depthpro2/code/tt_depthpro2/tests/test_device_mk_enc.py \ + -o faulthandler_timeout=1500 [-k S] +""" + +from __future__ import annotations + +import os + +import pytest +import torch + +from tt_depthpro2.reference import model as R +from tt_depthpro2.tests import mk_enc_ref as H + +ttnn = pytest.importorskip("ttnn") + +#: minimum tap PCC vs the float32 golden (bf16 weights / activations; the official bf16 run drifts similarly) +TAP_PCC = float(os.environ.get("MK_ENC_TAP_PCC", "0.995")) + +CASES = [ + ("S", "img_384x512", "depth"), + ("S", "clip4_240x320", "depth"), + ("S", "img_vga", "depth"), + ("B", "img_vga", "depth"), + ("B", "clip4_240x320", "depth"), + ("L", "img_vga", "depth"), + ("L", "clip4_240x320", "depth"), + ("H", "img_vga", "depth"), + ("H", "clip4_240x320", "depth"), + ("S", "img_384x512", "fov"), + ("S", "clip4_240x320", "fov"), +] + + +@pytest.fixture(scope="module") +def device(): + from tt_depthpro2.tests import baseline_helpers as BH + + dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), + l1_small_size=BH.L1_SMALL_SIZE, trace_region_size=224 << 20) + yield dev + ttnn.close_device(dev) + + +_W = {} + + +def weights(size: str): + if size not in _W: + _W.clear() + _W[size] = H.load_weights(size) + return _W[size] + + +def frames(case: str, size: str, mode: str) -> torch.Tensor: + g = H.load_case(case, "S" if mode == "fov" else size) + x = g["x_norm"].float() + return R.fov_resize(x) if mode == "fov" else R.pad_to_multiple(x) + + +def golden_taps(case: str, size: str, mode: str, w, x): + if mode == "depth": + g = H.load_case(case, size) + return [g[f"tap{i}"].float() for i in range(4)] + _, taps = H.ref_run(w, x, size, 12, mode) + return taps + + +def run_taps(dev, w, size: str, x: torch.Tensor, mode: str): + from tt_depthpro2.tt.mk_enc import arena as A + from tt_depthpro2.tt.mk_enc.program import MkEnc + + T, _, hp, wp = x.shape + mk = MkEnc(dev, w, size, T, hp // 16, wp // 16, mode=mode) + patches = ttnn.from_torch(A.patchify(x).to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, + device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) + taps = mk.run(patches) + out = [H.taps_from_device(ttnn.to_torch(t).float(), mk.geo) for t in taps] + return mk, patches, out + + +@pytest.mark.parametrize("size,case,mode", CASES, ids=[f"{s}-{c}-{m}" for s, c, m in CASES]) +def test_taps(device, size, case, mode): + w = weights("fov" if mode == "fov" else size) + x = frames(case, size, mode) + _, _, taps = run_taps(device, w, size, x, mode) + ref = golden_taps(case, size, mode, w, x) + for i, (d, r) in enumerate(zip(taps, ref)): + p, e = H.pcc(d, r), H.rel_err(d, r) + print(f"{size} {case} {mode} tap{i}: pcc {p:.6f} rel {e:.3e}") + assert p >= TAP_PCC, f"tap{i} pcc {p}" + + +@pytest.mark.parametrize("size,case", [("S", "img_384x512")]) +def test_determinism_and_trace(device, size, case): + w = weights(size) + x = frames(case, size, "depth") + mk, patches, first = run_taps(device, w, size, x, "depth") + raw = [ttnn.to_torch(t).clone() for t in mk.taps] + for _ in range(3): + mk.run(patches) + for a, t in zip(raw, mk.taps): + assert torch.equal(a, ttnn.to_torch(t)), "eager rerun not bitwise identical" + tid = ttnn.begin_trace_capture(device, cq_id=0) + mk.run(patches) + ttnn.end_trace_capture(device, tid, cq_id=0) + for _ in range(5): + ttnn.execute_trace(device, tid, cq_id=0, blocking=True) + for a, t in zip(raw, mk.taps): + assert torch.equal(a, ttnn.to_torch(t)), "trace replay not bitwise identical" + ttnn.release_trace(device, tid) + + +@pytest.mark.parametrize("size,case", [("S", "clip4_240x320")]) +def test_valid_frames(device, size, case): + """T-frame program + set_valid_frames(n) == the exact n-frame program (taps of frames < n), n = T unchanged.""" + from tt_depthpro2.tt.mk_enc import arena as A + from tt_depthpro2.tt.mk_enc.program import MkEnc, MkEncWeights + + x = frames(case, size, "depth") + T, _, hp, wp = x.shape + wts = MkEncWeights(device, weights(size), size, "depth") + + def dev_patches(f): + return ttnn.from_torch(A.patchify(f).to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, + device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) + + def taps(mk): + return [ttnn.to_torch(t).float().reshape(mk.geo.T, mk.geo.Np, -1)[:, :mk.geo.N] for t in mk.taps] + + mk = MkEnc(device, wts, size, T, hp // 16, wp // 16) + full_in = dev_patches(x) + mk.run(full_in) + first = [ttnn.to_torch(t).clone() for t in mk.taps] + for n in (2, 3): + xn = x.clone() + xn[n:] = 0 + mk.set_valid_frames(n) + mk.run(dev_patches(xn)) + got = taps(mk) + ex = MkEnc(device, wts, size, n, hp // 16, wp // 16) + ex.run(dev_patches(x[:n])) + for i, want in enumerate(taps(ex)): + p = H.pcc(got[i][:n], want) + print(f"valid frames {n}/{T} tap{i}: pcc vs exact T={n} {p:.7f}") + assert p >= 0.9999 + mk.set_valid_frames(T) + mk.run(full_in) + for a, t in zip(first, mk.taps): + assert torch.equal(a, ttnn.to_torch(t)), "n = T after n < T runs not bitwise identical" + + +def test_serve_configuration(device): + """Regression of the serve-pkg device smoke (S, buckets 480x640 / 640x480 / 256x320, window 4, clip lengths 1 / 4, + KV cache): every bucket x n = 1..3 clip on the T = 4 programs vs the fp32 reference, the golden clip4 between + them and after ttnn KV steps (tests/mk_enc_serve_repro.py).""" + from tt_depthpro2.tests.mk_enc_serve_repro import run_repro + + assert run_repro(device, "S", "mk", "ttnn") + + +@pytest.mark.parametrize("case", ["img_vga", "clip4_240x320", "img_375x500_pad"]) +def test_mk_fov(device, case): + """tt/mk_fov (FOV-mode megakernel trunk + ttnn fp32 head): f_px within max(1 %, 2 x official bf16 drift).""" + from tt_depthpro2.tests import baseline_helpers as BH + from tt_depthpro2.tt import StageShape, mk_fov + from tt_depthpro2.tt.mk_enc import arena as A + + g, _ = BH.load_golden(case, "S") + x = g["x_norm"].float() + T, _, h, w = x.shape + y = R.fov_resize(x) + eng = mk_fov.Engine(device, weights("fov"), StageShape(T, y.shape[-2], y.shape[-1])) + fp = ttnn.from_torch(A.patchify(y).to(torch.bfloat16).reshape(1, 1, -1, 768), dtype=ttnn.bfloat16, + layout=ttnn.TILE_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) + lg = ttnn.to_torch(eng.run(fp)).float().reshape(T, 2) + deg = R.fov_logits_to_deg(lg, (h, w), tuple(y.shape[-2:])) + f_rel = abs(float(R.median_focal_length_px(deg, h, w)) / float(g["focallength_px"]) - 1) + budget, _ = BH.fov_budget(case) + print(f"mk_fov {case}: f_rel {f_rel:.4%} (budget {budget:.2%})") + assert f_rel <= budget diff --git a/code/tt_depthpro2/tests/test_host_api.py b/code/tt_depthpro2/tests/test_host_api.py new file mode 100644 index 0000000000000000000000000000000000000000..cf1f5151d41d87e6b9cd37c1b608000dc0821435 --- /dev/null +++ b/code/tt_depthpro2/tests/test_host_api.py @@ -0,0 +1,335 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Host tests of the Python API (no device): ``DepthPro2`` on the CPU engine (``backend="cpu"``: the float32 +reference through the whole host pipeline) against Apple's float32 goldens -- images at a bucket size, an image +replicate-padded to a multiple of 32, a given focal length, a 4-frame clip -- and the host pipeline's own rules: the +resize to the nearest-aspect bucket and back with the focal length scaled, infinite depth where the inverse depth is +0, the output encodings, the clip-length and video-mode checks, the arguments handed to the device engine, the +weights resolution, warm-up and lifetime. + + PYTHONPATH=/research/packaging/scripts:code TT_VISIBLE_DEVICES=none \ + python -m pytest -p fake_ttnn_plugin code/tt_depthpro2/tests/test_host_api.py +""" +from __future__ import annotations + +import base64 +import io +import json + +import numpy as np +import pytest +import torch + +from tt_depthpro2 import config as C +from tt_depthpro2.api import DepthPro2, load_sample, resolve_weight_dirs +from tt_depthpro2.cpu_engine import CPUEngine +from tt_depthpro2.io import CapacityError, InputError +from tt_depthpro2.tests.host_helpers import WEIGHTS_ROOT, cpu_model, golden, need_weights, new_cpu_model, pcc, rel_err + +BUCKETS = "480x640,375x500,240x320" + + +def model(): + return cpu_model("S", resolutions=BUCKETS, window=4, overlap=1, clip_lengths="all") + + +# ---------------------------------------------------------------------------------------------- Apple's goldens + + +@pytest.mark.parametrize("case", ["img_vga__S", "img_375x500_pad__S"]) +def test_image_matches_the_official_golden(case): + g = golden(case) + out = model().infer(g["input_u8"].numpy()[0]) + assert not out.resized and out.device_size == C.padded_hw(*out.input_size) + assert out.inverse_depth.shape == g["inverse_depth"].shape + assert rel_err(out.inverse_depth, g["inverse_depth"]) < 1e-5 + assert pcc(out.inverse_depth, g["inverse_depth"]) > 0.999999 + f_gold = float(g["focallength_px"]) + assert out.focal_source == "fov" and abs(out.focallength_px - f_gold) / f_gold < 1e-3 + assert rel_err(out.depth, g["depth"]) < 1e-3 + assert torch.equal(torch.isinf(out.depth), torch.isinf(g["depth"])) + + +def test_image_with_f_px_matches_the_official_golden(): + g = golden("img_vga_fpx__S") + out = model().infer(g["input_u8"].numpy()[0], f_px=500.0) + assert out.focal_source == "request" and out.focallength_px == 500.0 and out.fov_deg is None + assert rel_err(out.depth, g["depth"]) < 1e-5 + + +def test_clip_matches_the_official_golden(): + g = golden("clip4_240x320__S") + m = model() + out = m.infer_clip(g["input_u8"].numpy()) + assert out.frames == 4 and out.inverse_depth.shape == (4, 240, 320) + assert rel_err(out.inverse_depth, g["inverse_depth"]) < 1e-5 + assert abs(out.focallength_px - float(g["focallength_px"])) / float(g["focallength_px"]) < 1e-3 + assert rel_err(out.depth, g["depth"]) < 1e-3 + assert len(out.fov_deg) == 4 + # a clip is not 4 images: the cross-frame blocks see all frames + single = m.infer(g["input_u8"].numpy()[0]) + assert rel_err(single.inverse_depth, g["inverse_depth"][0]) > 1e-4 + + +# ---------------------------------------------------------------------------------------------- host pipeline + + +def test_resize_to_bucket_and_back(): + g = golden("img_vga__S") + m = model() + u8 = g["input_u8"].numpy()[0] + big = u8.repeat(2, axis=0).repeat(2, axis=1) # 960 x 1280: same aspect as 480 x 640 -> resized + out = m.infer(big) + assert out.resized and out.bucket == (480, 640) and out.input_size == (960, 1280) + assert out.inverse_depth.shape == (960, 1280) and out.depth.shape == (960, 1280) + native = m.infer(u8) + assert abs(out.focallength_px / (2 * native.focallength_px) - 1) < 0.02 # focal in input pixels + pooled = torch.nn.functional.avg_pool2d(out.inverse_depth[None, None], 2)[0, 0] + assert pcc(pooled, native.inverse_depth) > 0.995 + # the depth comes from the input-size inverse depth and the input-pixel focal length + d = out.focallength_px / (1280 * out.inverse_depth) + assert rel_err(out.depth, d) < 1e-6 + # a 3:4 portrait input goes to... no portrait bucket here: the nearest aspect is 375 x 500 / 480 x 640 (4:3) + out2 = m.infer(np.ascontiguousarray(u8[:, :360])) # 480 x 360 + assert out2.resized and out2.inverse_depth.shape == (480, 360) + + +def test_infinite_depth_where_inverse_depth_is_zero(): + m = model() + out = m.infer(load_sample()) # the street photo has sky + inv0 = out.inverse_depth == 0 + assert inv0.any() and torch.equal(torch.isinf(out.depth), inv0) + assert bool((out.depth[~inv0] > 0).all()) + st = out.stats() + assert st["infinite_pixels"] == int(inv0.sum()) and 0 < st["min"] < st["median"] < st["max"] + + +def test_reference_outputs_of_the_sample_are_current(): + """The stored CPU references of the sample (used by the smoke test) equal what the API computes now.""" + from tt_depthpro2.api import SAMPLE_DIR + + m = model() + out = m.infer(load_sample()) + ref = json.loads((SAMPLE_DIR / "kropa_street" / "reference.S.json").read_text()) + pooled = np.load(SAMPLE_DIR / "kropa_street" / "reference.S.npy") + got = torch.nn.functional.avg_pool2d(out.inverse_depth[None, None], 4)[0, 0].numpy() + assert pooled.shape == (120, 160) and np.abs(got - pooled.astype(np.float32)).max() < 2e-3 * np.abs(got).max() + assert abs(ref["focallength_px"] - out.focallength_px) < 1e-3 + assert ref["weights"]["size"]["revision"] == C.WEIGHTS["S"][1] + assert ref["weights"]["focal"]["revision"] == C.WEIGHTS["focal"][1] + + +def test_output_encodings(): + m = model() + out = m.infer(load_sample()) + body = out.to_dict() + d = np.load(io.BytesIO(base64.b64decode(body["depth"]["data"]))) + assert d.dtype == np.float16 and d.shape == (480, 640) and body["depth"]["shape"] == [480, 640] + ref = out.depth.numpy() + fin = np.isfinite(ref) & (ref < 60000) + assert np.allclose(d[fin], ref[fin], rtol=1e-3) and np.isinf(d[np.isinf(ref)]).all() + b32 = out.to_dict("npy32", include_inverse_depth=True) + assert np.array_equal(np.load(io.BytesIO(base64.b64decode(b32["depth"]["data"]))), ref) + inv = np.load(io.BytesIO(base64.b64decode(b32["inverse_depth"]["data"]))) + assert np.array_equal(inv, out.inverse_depth.numpy()) + png = out.to_dict("png16", png_scale=100.0) + from PIL import Image + + im = np.asarray(Image.open(io.BytesIO(base64.b64decode(png["depth"]["data"])))) + assert im.shape == (480, 640) and im.dtype in (np.uint16, np.int32) + assert (im[np.isinf(ref)] == 0).all() and png["depth"]["infinite_pixels"] == int(np.isinf(ref).sum()) + near = np.isfinite(ref) & (ref < 600) + assert np.abs(im[near] / 100.0 - ref[near]).max() <= 0.006 + none = out.to_dict("none") + assert none["depth"] is None and none["stats_m"]["median"] > 0 + json.dumps(body) # JSON-serialisable + with pytest.raises(InputError): + out.to_dict("jpeg") + + +def test_input_checks(): + m = model() + for bad in (-1.0, 0, float("nan"), float("inf"), "x", True): + with pytest.raises(InputError): + m.infer(load_sample(), f_px=bad) + with pytest.raises(InputError): + m.infer(b"not an image") + with pytest.raises(InputError): + m.infer(np.zeros((8, 8, 3), np.uint8)) # below the minimum side + with pytest.raises(InputError): + m.infer_clip([np.zeros((240, 320, 3), np.uint8), np.zeros((480, 640, 3), np.uint8)]) + with pytest.raises(InputError): + m.infer_clip(np.zeros((5, 240, 320, 3), np.uint8)) # longer than the window + with pytest.raises(InputError): + list(m.infer_video([np.zeros((240, 320, 3), np.uint8)] * 3, mode="live")) # not a video mode + with pytest.raises(InputError): + list(m.infer_video([np.zeros((240, 320, 3), np.uint8)] * 3, window=5)) + with pytest.raises(InputError): + list(m.infer_video([np.zeros((240, 320, 3), np.uint8)] * 3, overlap=4)) + # float images in [0, 1] and (3, H, W) tensors are accepted + x = torch.rand(3, 240, 320) + a = m.infer(x, f_px=300.0) + b = m.infer((x.permute(1, 2, 0).numpy() * 255).round().astype(np.uint8), f_px=300.0) + assert torch.equal(a.inverse_depth, b.inverse_depth) + + +class ExactLengths(CPUEngine): + """A device engine WITHOUT a runtime valid-frame count (enc=mk until it has one): exactly the asked lengths.""" + + def __init__(self, *a, **kw): + super().__init__(*a, valid_frames=False, **kw) + + +def test_valid_frames_serve_every_length(): + need_weights("S") + with new_cpu_model("S", resolutions="240x320", window=4, overlap=1) as m: + assert m.clip_lengths == (1, 2, 3, 4) and m.compiled_clip_lengths == (1, 4) + assert m.info["configuration"]["valid_frames"] and m.info["configuration"]["compiled_clip_lengths"] == [1, 4] + frames = [np.full((240, 320, 3), 100 + k, np.uint8) for k in range(3)] + assert m.infer_clip(frames, f_px=200.0).frames == 3 + assert len(list(m.infer_video(frames, f_px=200.0))) == 3 # a video shorter than the window + + +def test_clip_lengths_are_enforced(): + need_weights("S") + with new_cpu_model("S", resolutions="240x320", window=4, overlap=1, engine_factory=ExactLengths) as m: + assert m.clip_lengths == (1, 4) and m.engine.clip_lengths == (1, 4) + frames = [np.full((240, 320, 3), 100 + k, np.uint8) for k in range(5)] + with pytest.raises(InputError, match="CLIP_LENGTHS"): + m.infer_clip(frames[:2]) + out = m.infer_clip(frames[:4], f_px=200.0) + assert out.frames == 4 + # a 3-frame video needs a 3-frame clip; a 7-frame one with overlap 1 only 4-frame clips + with pytest.raises(InputError, match="needs a clip"): + list(m.infer_video(frames[:3], f_px=200.0)) + assert len(list(m.infer_video(frames + frames[:2], f_px=200.0))) == 7 + # the FOV estimator runs in compiled chunks (frames are independent there): 3 frames = 3 x 1 + out = m.infer_video(frames + frames[:2]) + first = next(out) + assert first.focal_source == "fov" and first.focallength_px > 0 + out.close() + + +class Recorder(CPUEngine): + """A CPU engine with the plain DepthPro2Device constructor signature (no **kwargs): records what it was given.""" + + seen = {} + + def __init__(self, device, size, size_weights, fov_weights, buckets, max_frames, engine=None, frames=None): + Recorder.seen = dict(device=device, size=size, buckets=list(buckets), max_frames=max_frames, engine=engine, + frames=frames, fov=fov_weights is not None) + super().__init__(device, size, size_weights, fov_weights, buckets, max_frames, engine, frames, + clip_lengths=None, valid_frames=False) + + +def test_engine_arguments(): + need_weights("S") + m = DepthPro2.from_pretrained("s", resolutions="720p,240x320", window=6, overlap=2, clip_lengths="2", + engine="enc=mk,dec=ttnn", backend="cpu", engine_factory=Recorder, + weights_dir=str(WEIGHTS_ROOT), fov_weights_dir=str(WEIGHTS_ROOT), warmup=False) + try: + s = Recorder.seen + assert s["size"] == "S" and s["buckets"] == [(736, 1280), (256, 320)] and s["max_frames"] == 6 + assert s["frames"] == (1, 2) and s["engine"] == {"enc": "mk", "dec": "ttnn", "fov": "mk"} and s["fov"] + assert m.clip_lengths == (1, 2, 6) + info = m.info + json.dumps(info) + cfg = info["configuration"] + assert cfg["device_sizes"] == {"720x1280": [736, 1280], "240x320": [256, 320]} + assert cfg["fov_sizes"]["720x1280"] == [512, 896] and cfg["clip_lengths"] == [1, 2, 6] + assert info["weights"]["size"]["repo"] == "apple/DepthPro2-S" and info["license"]["notice"] == C.LICENSE_NOTICE + assert not info["supports_unbuffered"] or True + finally: + m.close() + m.close() # idempotent + with pytest.raises(RuntimeError): + m.infer(np.zeros((240, 320, 3), np.uint8)) + # precision the engine does not take is refused, as is unbuffered video without a KV cache + + class NoKV(Recorder): + supports_kv_cache = False + + with pytest.raises(ValueError, match="precision"): + DepthPro2.from_pretrained("S", resolutions="qvga", window=2, precision="bfp8", backend="cpu", + engine_factory=Recorder, weights_dir=str(WEIGHTS_ROOT), + fov_weights_dir=str(WEIGHTS_ROOT)) + with pytest.raises(NotImplementedError): + DepthPro2.from_pretrained("S", resolutions="qvga", window=2, video_modes="buffered,unbuffered", + backend="cpu", engine_factory=NoKV, weights_dir=str(WEIGHTS_ROOT), + fov_weights_dir=str(WEIGHTS_ROOT)) + + +def test_warmup_and_no_fov(): + need_weights("S", fov=False) + with new_cpu_model("S", resolutions="qvga", window=2, overlap=0, fov=False, warmup=True) as m: + assert set(m.warmup_latency_ms) == {"240x320/T1", "240x320/T2"} + out = m.infer(np.full((240, 320, 3), 90, np.uint8)) + assert out.depth is None and out.focallength_px is None and out.to_dict()["depth"] is None + assert m.infer(np.full((240, 320, 3), 90, np.uint8), f_px=250.0).depth is not None + assert m.info["weights"]["focal"] is None + + +def test_weights_resolution(tmp_path, monkeypatch): + need_weights("S") + sw, fw = resolve_weight_dirs("S", weights_dir=str(WEIGHTS_ROOT)) + assert sw["repo"] == "apple/DepthPro2-S" and sw["local"] and sw["revision"] in (None, C.WEIGHTS["S"][1]) + sw2, _ = resolve_weight_dirs("S", fov=False, weights_dir=str(WEIGHTS_ROOT / "DepthPro2-S")) + assert sw2["path"] == str(WEIGHTS_ROOT / "DepthPro2-S") + monkeypatch.setenv("DEPTHPRO2_WEIGHTS_DIR", str(tmp_path)) + with pytest.raises(FileNotFoundError): + resolve_weight_dirs("S", fov=False) + monkeypatch.delenv("DEPTHPRO2_WEIGHTS_DIR") + # a directory with another size's weights is refused at build + with pytest.raises(ValueError, match="DepthPro2-B"): + DepthPro2.from_pretrained("B", resolutions="qvga", window=2, backend="cpu", + weights_dir=str(WEIGHTS_ROOT / "DepthPro2-S"), fov=False) + with pytest.raises(ValueError): + DepthPro2.from_pretrained("S", backend="gpu") + with pytest.raises(TypeError): + DepthPro2() + + +def test_unbuffered_streams_are_limited_by_kv_streams(): + need_weights("S") + with new_cpu_model("S", resolutions="240x320", window=3, overlap=1, video_modes="buffered,unbuffered") as m: + assert "unbuffered" in m.config.video_modes and m.config.kv_streams == 1 + f = np.full((240, 320, 3), 90, np.uint8) + a = m.stream(f_px=200.0, mode="unbuffered") + assert [o.frame_index for o in a.step(f)] == [0] + b = m.stream(f_px=200.0, mode="unbuffered") + with pytest.raises(CapacityError): + b.step(f) + b.close() + with pytest.raises(CapacityError): + list(m.infer_video([f, f], f_px=200.0, mode="unbuffered")) + a.close() + assert m._kv_open == 0 + assert len(list(m.infer_video([f, f], f_px=200.0, mode="unbuffered"))) == 2 and m._kv_open == 0 + plan = m.info["configuration"]["kv_cache"] + assert plan["caches"] == 1 and plan["per_cache_bytes"] > 0 + + +def test_auto_video_modes_follow_the_kv_budget(): + need_weights("S", fov=False) + with new_cpu_model("S", resolutions="qvga", window=4, fov=False) as m: # small caches: unbuffered on + assert m.config.video_modes == ("buffered", "unbuffered") and "on" in m.video_modes_reason + # 8 streams x 2 buckets of 1080p, window 16 (720 MB per S cache): far above the budget -> buffered only + with new_cpu_model("S", resolutions="1080p,1080p_portrait", window=16, kv_streams=8, fov=False) as m: + assert m.config.video_modes == ("buffered",) and "off" in m.video_modes_reason + assert m.kv_cache_plan()["total_bytes"] > C.KV_BUDGET_BYTES + # explicit modes are kept + with new_cpu_model("S", resolutions="1080p", window=16, kv_streams=8, fov=False, + video_modes="buffered,unbuffered") as m: + assert m.config.video_modes == ("buffered", "unbuffered") + + +def test_trace_region_is_sized_from_the_configuration(monkeypatch): + from tt_depthpro2.device import trace_region_for + + monkeypatch.delenv("DEPTHPRO2_TRACE_REGION", raising=False) + fov = [(480, 640), (640, 480)] + small = trace_region_for("S", [(480, 640), (640, 480)], 16, clip_lengths=(1, 16), fov_shapes=fov) + big = trace_region_for("L", [(480, 640), (640, 480)], 16, clip_lengths=(1, 16), fov_shapes=fov, kv_cache=True) + huge = trace_region_for("H", [(1088, 1920)], 16, clip_lengths=(1, 16), fov_shapes=[(512, 896)], kv_cache=True) + assert small % (32 << 20) == 0 and small < big < huge and huge > (256 << 20) # the old fixed 256 MB is too small + monkeypatch.setenv("DEPTHPRO2_TRACE_REGION", str(512 << 20)) + assert trace_region_for("S", [(480, 640)], 16) is None # the environment wins (DeviceConfig.from_env reads it) diff --git a/code/tt_depthpro2/tests/test_host_bundle.py b/code/tt_depthpro2/tests/test_host_bundle.py new file mode 100644 index 0000000000000000000000000000000000000000..02ad78fed207b9398154951b61ae28080513055b --- /dev/null +++ b/code/tt_depthpro2/tests/test_host_bundle.py @@ -0,0 +1,224 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Host tests of the bundle wiring (no device, no weights): the vendored ttaw copy is intact; the server, config and +smoke modules import without ttnn / torch; tt-model.yaml agrees with config.py (weights pins, serve env, profiles) +and its serve env starts the server's configuration; the shipped sample, its references and the licence notices +are what tt-model.yaml verifies; the stdlib helpers of the smoke test and the client work; container_smoke.sh +parses; the pip project is the repo-root pyproject.toml. + + PYTHONPATH=/research/packaging/scripts:code TT_VISIBLE_DEVICES=none \ + python -m pytest -p fake_ttnn_plugin code/tt_depthpro2/tests/test_host_bundle.py +""" +from __future__ import annotations + +import fnmatch +import hashlib +import importlib.util +import io +import json +import os +import subprocess +import sys +from pathlib import Path + +import numpy as np +import pytest + +import tt_depthpro2 +from tt_depthpro2 import config as C + +PKG_DIR = Path(tt_depthpro2.__file__).resolve().parent +CODE_DIR, BUNDLE_DIR, TTAW_DIR = PKG_DIR.parent, PKG_DIR.parents[1], PKG_DIR / "ttaw" +YAML = BUNDLE_DIR / "tt-model.yaml" +SAMPLE = PKG_DIR / "samples" / "kropa_street" +VENDOR_IGNORE = ("__pycache__", "*.pyc", "*.pyo", ".pytest_cache", "*.bin", "*.log", ".DS_Store", "VENDORED.json") + +BLOCKER = """ +import importlib, importlib.abc, sys +BLOCKED = set(sys.argv[2].split(",")) +class Block(importlib.abc.MetaPathFinder): + def find_spec(self, name, path, target=None): + if name.split(".")[0] in BLOCKED: + raise ImportError("blocked import of " + name) +sys.meta_path.insert(0, Block()) +sys.path.insert(0, sys.argv[1]) +for module in sys.argv[3:]: + importlib.import_module(module) +print("ok") +""" + + +def _yaml(): + yaml = pytest.importorskip("yaml") + return yaml.safe_load(YAML.read_text()) + + +def _load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + spec.loader.exec_module(mod) + return mod + + +def test_vendored_ttaw_is_intact(): + rec = json.loads((TTAW_DIR / "VENDORED.json").read_text()) + assert rec["package"] == "ttaw" and not rec["source_dirty"] and len(rec["source_commit"]) == 40 + have = {} + for p in sorted(TTAW_DIR.rglob("*")): + rel = p.relative_to(TTAW_DIR) + if p.is_file() and not any(fnmatch.fnmatch(part, pat) for part in rel.parts for pat in VENDOR_IGNORE): + have[rel.as_posix()] = hashlib.sha256(p.read_bytes()).hexdigest() + assert have == rec["files"], "the vendored ttaw was edited: re-vendor with common/tools/vendor.py" + + +def _same_path_env(): + """The subprocess sees the modules this process sees (pytest may run with a PYTHONPATH that lacks, e.g., the + directory providing fastapi while conftest / plugins added others to sys.path).""" + import os + + env = dict(os.environ) + env["PYTHONPATH"] = os.pathsep.join(p for p in sys.path if p) + return env + + +def test_imports_without_ttnn_and_torch(): + import importlib.util + + mods = ["tt_depthpro2", "tt_depthpro2.config", "tt_depthpro2.io", "tt_depthpro2.device", "tt_depthpro2.server"] + if importlib.util.find_spec("fastapi") is not None: # the server needs the [server] extras + mods.append("tt_depthpro2.server.app") + r = subprocess.run([sys.executable, "-c", BLOCKER, str(CODE_DIR), "ttnn,torch"] + mods, capture_output=True, + text=True, env=_same_path_env()) + assert r.returncode == 0 and r.stdout.strip() == "ok", r.stderr[-2000:] + # the API module imports without ttnn (torch only when a model is built) + r = subprocess.run([sys.executable, "-c", BLOCKER, str(CODE_DIR), "ttnn,torch", "tt_depthpro2.api"], + capture_output=True, text=True, env=_same_path_env()) + assert r.returncode == 0, r.stderr[-2000:] + + +def test_stdlib_scripts_run_under_plain_python(): + """smoke_test.py and client.py run with the host's python3 (no numpy, no package installed).""" + blocker = BLOCKER.replace("for module in sys.argv[3:]:\n importlib.import_module(module)\n", "") + for script in (PKG_DIR / "server" / "smoke_test.py", PKG_DIR / "server" / "client.py"): + code = blocker + f"\nimport runpy, sys\nsys.argv = ['{script.name}', '--help']\n" \ + f"try:\n runpy.run_path({str(script)!r}, run_name='__main__')\nexcept SystemExit as e:\n" \ + f" assert e.code in (0, None), e.code\n" + r = subprocess.run([sys.executable, "-I", "-c", code, "/nonexistent", "numpy,torch,ttnn,tt_depthpro2,PIL"], + capture_output=True, text=True, cwd="/") + assert r.returncode == 0, (script.name, r.stderr[-2000:]) + + +def test_manifest_agrees_with_config(): + y = _yaml() + assert y["repo"] == C.PACKAGE_REPO and y["name"] == C.MODEL_NAME and y["kind"] == "tt-dit-server" + assert (y["weights"]["repo"], y["weights"]["revision"]) == C.WEIGHTS["focal"] + aux = {(a["repo"], a["revision"]) for a in y["auxiliary_weights"]} + assert aux == {C.WEIGHTS[s] for s in C.SIZES} + for w in [y["weights"]] + y["auxiliary_weights"]: + assert w["allow_patterns"] == C.ALLOW_PATTERNS + env = y["serve"]["env"] + assert env["TT_WEIGHTS_REVISION"] == C.WEIGHTS["focal"][1] and env["DEPTHPRO2_DISPATCH"] == "eth" + assert {p["name"]: p["env"]["DEPTHPRO2_SIZE"] for p in y["serve_profiles"]} == {k: v for k, v in C.PROFILES.items()} + assert y["default_profile"] == "l" + assert y["runtime"]["app"] == "tt_depthpro2.server.app:app" + for path in y["source"]["extra_code"][0]["paths"]: + assert (CODE_DIR / path).exists(), path + card = y["card"] + assert card["license"]["id"] == "other" and card["license"]["name"] and "LICENSE" in card["license"]["link"] + assert card["pipeline_tag"] == "depth-estimation" + assert set(card["base_model"]) == {C.WEIGHTS[k][0] for k in C.WEIGHTS} + for field in ("attribution", "licensing"): + text = " ".join(card[field].split()) + assert C.LICENSE_NOTICE in text, field + assert "research purposes only" in card["licensing"] and "not affiliated with or endorsed by Apple" in \ + " ".join(card["attribution"].split()) + + +def test_serve_env_starts_the_pinned_configuration(): + pytest.importorskip("fastapi") + from tt_depthpro2.server.app import load_config + + y = _yaml() + aux = ",".join(f"{a['repo']}@{a['revision']}" for a in y["auxiliary_weights"]) + for p in y["serve_profiles"]: + env = dict(y["serve"]["env"], **p["env"], TT_AUXILIARY_WEIGHTS=aux, + TT_MODEL_WEIGHTS_REVISION=y["weights"]["revision"], HF_MODEL=y["weights"]["repo"], + TT_MESH_SHAPE="1x1") + c = load_config(env) + size = C.PROFILES[p["name"]] + assert c.model.size == size and c.revision == C.WEIGHTS[size][1] and c.fov_revision == C.WEIGHTS["focal"][1] + assert (c.model.resolutions, c.model.window, c.model.overlap) == (((480, 640), (640, 480)), 16, 4) + + +def test_sample_references_and_licences(): + y = _yaml() + meta = json.loads((SAMPLE / "sample.json").read_text()) + img = SAMPLE / meta["file"] + sha = hashlib.sha256(img.read_bytes()).hexdigest() + assert any(sha in v for v in y["verify"]), "tt-model.yaml verifies another sample image" + assert "CC0" in meta["license"] and "CC0" in (SAMPLE / "PROVENANCE.md").read_text() + from PIL import Image + + with Image.open(img) as im: + assert im.size == (640, 480) and not dict(im.getexif()) # no EXIF (the original had GPS) + for s in C.SIZES: + ref = json.loads((SAMPLE / f"reference.{s}.json").read_text()) + arr = np.load(SAMPLE / f"reference.{s}.npy") + assert ref["size"] == s and ref["input_size"] == [480, 640] and arr.shape == (120, 160) + assert arr.dtype == np.float16 and np.isfinite(arr).all() and (arr >= 0).all() + assert ref["weights"]["size"]["revision"] == C.WEIGHTS[s][1] + assert ref["weights"]["focal"]["revision"] == C.WEIGHTS["focal"][1] and ref["focal_source"] == "fov" + notice = " ".join((PKG_DIR / "licenses" / "NOTICE.md").read_text().split()) + assert C.LICENSE_NOTICE in notice and "not made, affiliated with, endorsed or supported by Apple" in notice + lic = (PKG_DIR / "licenses" / "APPLE_MLR_MODEL_LICENSE.txt").read_bytes() + assert b"Research Purposes" in lic and b"Model Derivatives" in lic + # Apple's software licence of ml-depth-pro-2, under which streaming.py follows the structure of Apple's streaming.py + sw = (PKG_DIR / "licenses" / "APPLE_SOFTWARE_LICENSE.txt").read_bytes() + assert sw.startswith(b"Copyright (C) 2026 Apple Inc.") and b'"Apple Software"' in sw + assert "APPLE_SOFTWARE_LICENSE.txt" in notice and "streaming.py" in notice + assert "APPLE_SOFTWARE_LICENSE.txt" in (PKG_DIR / "streaming.py").read_text().split('"""')[0] + # optional cross-checks against the upstream files (DEPTHPRO2_UPSTREAM_LICENSE: the model repo's LICENSE, + # DEPTHPRO2_UPSTREAM_CODE_LICENSE: ml-depth-pro-2's LICENSE) + for var, data in (("DEPTHPRO2_UPSTREAM_LICENSE", lic), ("DEPTHPRO2_UPSTREAM_CODE_LICENSE", sw)): + upstream = Path(os.environ.get(var) or "/nonexistent") + if upstream.is_file(): + assert upstream.read_bytes() == data, var + + +def test_smoke_helpers(): + smoke = _load("dp2_smoke_t", PKG_DIR / "server" / "smoke_test.py") + for dt in (np.float16, np.float32): + a = (np.arange(48, dtype=np.float32).reshape(6, 8) / 7).astype(dt) + buf = io.BytesIO() + np.save(buf, a) + shape, vals = smoke.parse_npy(buf.getvalue()) + assert shape == (6, 8) and np.allclose(vals, a.astype(np.float32).ravel()) + pooled = smoke.avg_pool(vals, 6, 8, 2) + assert np.allclose(pooled, a.astype(np.float32).reshape(3, 2, 4, 2).mean(axis=(1, 3)).ravel(), atol=1e-6) + x = list(np.random.default_rng(0).normal(size=100)) + assert abs(smoke.pcc(x, [2 * v + 1 for v in x]) - 1) < 1e-12 + tiny = smoke._tiny_png(32, 32) + assert smoke.png_ihdr(tiny) == (32, 32, 8, 2) + from PIL import Image + + assert Image.open(io.BytesIO(tiny)).size == (32, 32) + + +def test_client_requests(): + client = _load("dp2_client_t", PKG_DIR / "server" / "client.py") + body = client.sample_request(f_px=400.0, output_format="npy32") + assert body["f_px"] == 400.0 and body["output_format"] == "npy32" and len(body["image"]) > 1000 + tiny = _load("dp2_smoke_t2", PKG_DIR / "server" / "smoke_test.py")._tiny_png(16, 16) + frames = client.png_frames_from_stream(tiny * 3) + assert frames == [tiny] * 3 + v = client.build_video_request([tiny, tiny], mode="clip", stream_id="a", end=True) + assert v["mode"] == "clip" and len(v["frames"]) == 2 and v["stream"] == {"id": "a", "end": True} + assert "image" not in client.summarize({"depth": {"data": "x" * 10}}) + + +def test_container_smoke_script_and_pyproject(): + r = subprocess.run(["bash", "-n", str(CODE_DIR / "scripts" / "container_smoke.sh")], capture_output=True) + assert r.returncode == 0, r.stderr + assert (BUNDLE_DIR / "pyproject.toml").is_file() and not (CODE_DIR / "pyproject.toml").exists() + text = (BUNDLE_DIR / "pyproject.toml").read_text() + assert 'include = ["tt_depthpro2*"]' in text and '"tt_depthpro2" = ["samples/*/*", "licenses/*"]' in text diff --git a/code/tt_depthpro2/tests/test_host_config.py b/code/tt_depthpro2/tests/test_host_config.py new file mode 100644 index 0000000000000000000000000000000000000000..9edf3b3390ab09099f1176a695d80b206e805e71 --- /dev/null +++ b/code/tt_depthpro2/tests/test_host_config.py @@ -0,0 +1,151 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Host tests of the configuration surface (no device, no weights): sizes and profiles, resolution buckets and +presets, window / overlap / clip lengths / video modes / engine / precision validation, the bucket choice, the +weights pins, and the server's start-up configuration (``server.app.load_config``) including its refusals. + + PYTHONPATH=/research/packaging/scripts:code TT_VISIBLE_DEVICES=none \ + python -m pytest -p fake_ttnn_plugin code/tt_depthpro2/tests/test_host_config.py +""" +from __future__ import annotations + +import pytest + +from tt_depthpro2 import config as C + + +def test_sizes_and_profiles(): + for raw, want in (("S", "S"), ("s", "S"), ("small", "S"), ("b", "B"), ("L", "L"), ("large", "L"), ("H", "H"), + ("h+", "H"), ("H+", "H"), ("huge_plus", "H"), ("DepthPro2-L", "L"), ("apple/DepthPro2-B", "B")): + assert C.normalize_size(raw) == want, raw + for bad in ("XL", "", None, 3, "m"): + with pytest.raises(ValueError): + C.normalize_size(bad) + assert C.PROFILES == {"s": "S", "b": "B", "l": "L", "h": "H"} + assert set(C.WEIGHTS) == {"focal", "S", "B", "L", "H"} + for k, (repo, rev) in C.WEIGHTS.items(): + assert repo.startswith("apple/DepthPro2-") and len(rev) == 40 and int(rev, 16) >= 0 + + +def test_resolutions_presets_and_validation(): + assert C.parse_resolutions(None) == ((480, 640), (640, 480)) + assert C.parse_resolutions("vga, 720p ,480x640, 1080p_portrait") == ((480, 640), (720, 1280), (1920, 1080)) + assert C.parse_resolutions("375X500") == ((375, 500),) + assert C.parse_resolutions([(240, 320), "qvga_portrait"]) == ((240, 320), (320, 240)) + assert C.parse_resolutions((480, 640)) == ((480, 640),) + for bad in ("480x", "abc", "16x640", "480x5000", "0x0", "", [(1.5, 2)], [(True, 4)], + ",".join(["vga", "qvga", "square", "720p", "1080p", "vga_portrait", "qvga_portrait", "720p_portrait", + "1080p_portrait"])): + with pytest.raises(ValueError): + C.parse_resolutions(bad) + assert C.padded_hw(720, 1280) == (736, 1280) and C.padded_hw(1080, 1920) == (1088, 1920) + assert C.padded_hw(375, 500) == (384, 512) and C.padded_hw(480, 640) == (480, 640) + + +def test_choose_bucket(): + b = [(480, 640), (640, 480), (720, 1280)] + assert C.choose_bucket(480, 640, b) == ((480, 640), True) + assert C.choose_bucket(960, 1280, b) == ((480, 640), False) # same aspect, resized + assert C.choose_bucket(1080, 1920, b) == ((720, 1280), False) # 16:9 + assert C.choose_bucket(1280, 960, b) == ((640, 480), False) # portrait + assert C.choose_bucket(470, 630, b) == ((480, 640), False) # never padded natively unless exactly a bucket + # same aspect ratio: the nearest area wins + assert C.choose_bucket(300, 400, [(480, 640), (240, 320)]) == ((240, 320), False) + assert C.choose_bucket(700, 1000, [(480, 640), (240, 320)]) == ((480, 640), False) + + +def test_resolve_config_defaults_env_and_explicit(): + c = C.resolve_config(env={}) + assert (c.size, c.resolutions, c.window, c.overlap, c.video_modes, c.clip_lengths, c.fov, c.engine, + c.precision) == ("L", ((480, 640), (640, 480)), 16, 4, ("buffered", "unbuffered"), (1, 16), True, + {"enc": "mk", "dec": "mk", "fov": "mk"}, None) + assert c.video_modes_auto and c.kv_streams == 1 and c.as_env()["DEPTHPRO2_VIDEO_MODES"] == "auto" + assert C.resolve_config(env={"DEPTHPRO2_VIDEO_MODES": "AUTO"}).video_modes_auto + b = C.resolve_config(video_modes="buffered", kv_streams="3", env={}) + assert b.video_modes == ("buffered",) and not b.video_modes_auto and b.kv_streams == 3 + env = {"DEPTHPRO2_SIZE": "h", "DEPTHPRO2_RESOLUTIONS": "720p", "DEPTHPRO2_WINDOW": "8", "DEPTHPRO2_OVERLAP": "2", + "DEPTHPRO2_VIDEO_MODES": "unbuffered,buffered", "DEPTHPRO2_CLIP_LENGTHS": "2,4", "DEPTHPRO2_FOV": "0", + "DEPTHPRO2_ENGINE": "enc=mk,dec=ttnn", "DEPTHPRO2_PRECISION": "BF16", "DEPTHPRO2_KV_STREAMS": "2"} + c = C.resolve_config(env=env) + assert (c.size, c.resolutions, c.window, c.overlap, c.video_modes, c.clip_lengths, c.fov, c.engine, + c.precision) == ("H", ((720, 1280),), 8, 2, ("buffered", "unbuffered"), (1, 2, 4, 8), False, + {"enc": "mk", "dec": "ttnn", "fov": "mk"}, "bf16") # dec=ttnn given explicitly + assert c.device_buckets == [(736, 1280)] + assert C.resolve_config(env=c.as_env()) == c # as_env round-trips + # explicit arguments win over the environment + c2 = C.resolve_config("S", window=2, overlap=1, resolutions="qvga", clip_lengths="auto", env=env) + assert (c2.size, c2.window, c2.overlap, c2.resolutions, c2.clip_lengths) == ("S", 2, 1, ((240, 320),), (1, 2)) + # unset overlap is clamped below the window; "all" clip lengths + assert C.resolve_config(window=3, env={}).overlap == 2 + assert C.resolve_config(window=1, env={}).overlap == 0 + assert C.resolve_config(window=4, clip_lengths="all", env={}).clip_lengths == (1, 2, 3, 4) + assert C.parse_engine("ttnn") == {"enc": "ttnn", "dec": "ttnn", "fov": "ttnn"} + assert C.parse_engine("") == C.DEFAULT_ENGINE == {"enc": "mk", "dec": "mk", "fov": "mk"} + assert C.parse_engine({"fov": "TTNN"}) == {"enc": "mk", "dec": "mk", "fov": "ttnn"} # unnamed stages: default + assert C.parse_engine("enc=ttnn") == {"enc": "ttnn", "dec": "mk", "fov": "mk"} + + +def test_ttnn_decoder_fallback_and_no_guard(): + assert C.resolve_config(env={"DEPTHPRO2_ENGINE": "dec=ttnn"}).engine == {"enc": "mk", "dec": "ttnn", "fov": "mk"} + assert C.resolve_config(env={"DEPTHPRO2_ENGINE": "ttnn"}).engine == {"enc": "ttnn", "dec": "ttnn", "fov": "ttnn"} + # the decoder megakernel needs no flag any more; a left-over DEPTHPRO2_EXPERIMENTAL_MK_DEC is ignored + for flag in (None, "0", "1"): + env = {"DEPTHPRO2_ENGINE": "dec=mk"} if flag is None else {"DEPTHPRO2_ENGINE": "dec=mk", + "DEPTHPRO2_EXPERIMENTAL_MK_DEC": flag} + assert C.resolve_config(env=env).engine["dec"] == "mk" + + +@pytest.mark.parametrize("env", [ + {"DEPTHPRO2_SIZE": "XL"}, {"DEPTHPRO2_RESOLUTIONS": "480x"}, {"DEPTHPRO2_WINDOW": "0"}, + {"DEPTHPRO2_WINDOW": "17"}, {"DEPTHPRO2_WINDOW": "4.5"}, {"DEPTHPRO2_OVERLAP": "16"}, + {"DEPTHPRO2_OVERLAP": "4", "DEPTHPRO2_WINDOW": "4"}, {"DEPTHPRO2_OVERLAP": "-1"}, + {"DEPTHPRO2_VIDEO_MODES": "live"}, {"DEPTHPRO2_CLIP_LENGTHS": "17"}, {"DEPTHPRO2_CLIP_LENGTHS": "x"}, + {"DEPTHPRO2_FOV": "maybe"}, {"DEPTHPRO2_KV_STREAMS": "0"}, {"DEPTHPRO2_KV_STREAMS": "9"}, {"DEPTHPRO2_ENGINE": "enc=gpu"}, {"DEPTHPRO2_ENGINE": "foo=mk"}, + {"DEPTHPRO2_ENGINE": "megakernel"}, {"DEPTHPRO2_PRECISION": "fp8"}, +]) +def test_resolve_config_refuses(env): + with pytest.raises(ValueError) as e: + C.resolve_config(env=env) + assert next(iter(env)) in str(e.value) # the message names the variable + + +def test_auxiliary_weights_parsing(): + aux = C.parse_auxiliary_weights("apple/DepthPro2-S@abc, apple/DepthPro2-B ,x@") + assert aux == {"apple/DepthPro2-S": "abc", "apple/DepthPro2-B": None, "x": None} + assert C.parse_auxiliary_weights(None) == {} + + +def _server_env(**over): + env = {"DEPTHPRO2_SIZE": "L", "TT_AUXILIARY_WEIGHTS": ",".join(f"{r}@{v}" for k, (r, v) in C.WEIGHTS.items() + if k != "focal"), + "TT_MODEL_WEIGHTS_REVISION": C.WEIGHTS["focal"][1], "HF_MODEL": "apple/DepthPro2-focal", + "TT_MESH_SHAPE": "1x1"} + env.update(over) + return env + + +def test_server_load_config(): + pytest.importorskip("fastapi") + from tt_depthpro2.server.app import load_config + + c = load_config(_server_env()) + assert c.model.size == "L" and c.revision == C.WEIGHTS["L"][1] and c.fov_revision == C.WEIGHTS["focal"][1] + assert (c.dispatch, c.num_command_queues, c.backend, c.max_frames, c.max_streams) == ("eth", None, "tt", 64, 4) + c = load_config(_server_env(DEPTHPRO2_SIZE="S", DEPTHPRO2_NUM_CQS="2", DEPTHPRO2_DISPATCH="WORKER", + DEPTHPRO2_MAX_FRAMES="8", TT_DEVICE_ID="1")) + assert (c.model.size, c.revision, c.num_command_queues, c.dispatch, c.max_frames, c.device_id) == ( + "S", C.WEIGHTS["S"][1], 2, "worker", 8, 1) + assert load_config({}).revision is None # no tt-model env: the API's pins apply + + +@pytest.mark.parametrize("over", [ + {"TT_MESH_SHAPE": "1x2"}, {"TT_MESH_SHAPE": "two"}, {"DEPTHPRO2_DISPATCH": "auto"}, {"DEPTHPRO2_NUM_CQS": "3"}, + {"DEPTHPRO2_BACKEND": "gpu"}, {"TT_DEVICE_ID": "x"}, {"HF_MODEL": "apple/DepthPro2-L"}, + {"DEPTHPRO2_MAX_FRAMES": "0"}, {"DEPTHPRO2_MAX_BODY_MB": "huge"}, {"DEPTHPRO2_SIZE": "XXL"}, + {"DEPTHPRO2_RESOLUTIONS": "100000x2"}, {"DEPTHPRO2_OVERLAP": "99"}, +]) +def test_server_load_config_refuses(over): + pytest.importorskip("fastapi") + from tt_depthpro2.server.app import load_config + + with pytest.raises(RuntimeError): + load_config(_server_env(**over)) diff --git a/code/tt_depthpro2/tests/test_host_server.py b/code/tt_depthpro2/tests/test_host_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2330f414646d330907319c005f7d9abe0cefe43c --- /dev/null +++ b/code/tt_depthpro2/tests/test_host_server.py @@ -0,0 +1,352 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Host tests of the HTTP server (no device): the real app with the API on the CPU engine (Depth Pro 2 S): routes, +/health before and after start-up, /info and /config, ``/predict`` (every output format; API == server), the 16-bit +PNG route, ``/predict_video`` (buffered, one clip, a stream across requests and its limit), the 400 / 422 / 429 / 500 +/ 503 answers, start-up refusals, and the stdlib smoke test against the app served over real HTTP by uvicorn. + + PYTHONPATH=/research/packaging/scripts:code TT_VISIBLE_DEVICES=none \ + python -m pytest -p fake_ttnn_plugin code/tt_depthpro2/tests/test_host_server.py +""" +from __future__ import annotations + +import base64 +import contextlib +import io +import json +import socket +import threading +from pathlib import Path + +import numpy as np +import pytest + +fastapi = pytest.importorskip("fastapi") +from fastapi.testclient import TestClient # noqa: E402 + +from tt_depthpro2.api import DepthPro2, load_sample # noqa: E402 +from tt_depthpro2.server import app as server # noqa: E402 +from tt_depthpro2.tests.host_helpers import WEIGHTS_ROOT, golden, need_weights, rel_err # noqa: E402 + +SMOKE = Path(server.__file__).resolve().parent / "smoke_test.py" +ENV = {"DEPTHPRO2_SIZE": "S", "DEPTHPRO2_RESOLUTIONS": "480x640,240x320", "DEPTHPRO2_WINDOW": "2", + "DEPTHPRO2_OVERLAP": "1", "DEPTHPRO2_BACKEND": "cpu", "DEPTHPRO2_MAX_FRAMES": "8", "DEPTHPRO2_MAX_STREAMS": "1", + "DEPTHPRO2_WEIGHTS_DIR": str(WEIGHTS_ROOT), "DEPTHPRO2_FOV_WEIGHTS_DIR": str(WEIGHTS_ROOT)} +FAKE_DEVICE = {"dispatch": "eth", "grid": "12x10", "cores": 120, "num_command_queues": 1, "backend": "cpu"} + + +def cpu_factory(cfg, warmup=False): + """``default_model_factory`` on the CPU engine (without the warm-up unless asked), reporting the p150's device + fields (the smoke test asserts ETH dispatch and the 12x10 grid).""" + m = cfg.model + model = DepthPro2.from_pretrained(m.size, resolutions=m.resolutions, window=m.window, overlap=m.overlap, + fov=m.fov, video_modes=m.video_modes, clip_lengths=m.clip_lengths, + weights_dir=cfg.weights_dir, fov_weights_dir=cfg.fov_weights_dir, + backend="cpu", warmup=warmup) + model.device_info = dict(FAKE_DEVICE) + return model + + +@contextlib.contextmanager +def client_with(monkeypatch, factory=cpu_factory, **env): + need_weights("S") + for k, v in dict(ENV, **env).items(): + if v is None: + monkeypatch.delenv(k, raising=False) + else: + monkeypatch.setenv(k, v) + st = server.app.state.dp2 + old = (st.model_factory, st.model, st.config, st.ready, st.error) + st.model_factory, st.model, st.config, st.ready, st.error = factory, None, None, False, None + try: + with TestClient(server.app) as c: + yield c + finally: + st.model_factory, st.model, st.config, st.ready, st.error = old + st.streams.clear() + + +@pytest.fixture(scope="module") +def mp_module(): + mp = pytest.MonkeyPatch() + yield mp + mp.undo() + + +@pytest.fixture(scope="module") +def client(mp_module): + with client_with(mp_module) as c: + yield c + + +def b64(raw: bytes) -> str: + return base64.b64encode(raw).decode("ascii") + + +def png_bytes(a: np.ndarray) -> bytes: + from PIL import Image + + buf = io.BytesIO() + Image.fromarray(a).save(buf, format="PNG") + return buf.getvalue() + + +def npy(d): + return np.load(io.BytesIO(base64.b64decode(d["data"]))) + + +SAMPLE = load_sample().read_bytes() + + +def test_routes_health_info(client): + assert "POST /predict_video" in client.get("/").json()["routes"] + h = client.get("/health").json() + assert h["status"] == "ok" and h["device"]["grid"] == "12x10" + assert client.get("/v1/health").json()["status"] == "ok" + info = client.get("/info").json() + assert info["model"] == "depthpro2" and info["size"] == "S" and info["backend"] == "cpu" + assert info["configuration"]["resolutions"] == [[480, 640], [240, 320]] + assert info["configuration"]["clip_lengths"] == [1, 2] and info["weights"]["repo"] == "apple/DepthPro2-focal" + assert info["server"]["limits"]["max_frames_per_request"] == 8 + assert "Research Model License" in info["license"]["notice"] + cfg = client.get("/config").json() + assert cfg["configuration"]["window"] == 2 and cfg["limits"]["max_streams"] == 1 + assert client.get("/v1/models").json()["data"][0]["id"] == "apple/DepthPro2-S" + + +def test_predict_equals_the_api(client): + r = client.post("/predict", json={"image": b64(SAMPLE), "include_inverse_depth": True}) + assert r.status_code == 200, r.text + body = r.json() + assert body["input_size"] == [480, 640] and not body["resized"] and body["focal_source"] == "fov" + assert set(body["timing_ms"]) >= {"decode", "preprocess", "device", "fov", "postprocess", "encode", "total"} + api = server.app.state.dp2.model.infer(load_sample()).to_dict(include_inverse_depth=True) + assert body["depth"]["data"] == api["depth"]["data"] and body["inverse_depth"]["data"] == api["inverse_depth"]["data"] + assert body["focallength_px"] == api["focallength_px"] and body["stats_m"] == api["stats_m"] + d = npy(body["depth"]) + assert d.dtype == np.float16 and d.shape == (480, 640) and np.isinf(d).any() + + +def test_predict_options(client): + r = client.post("/predict", json={"image": b64(SAMPLE), "f_px": 400.0, "output_format": "npy32"}).json() + assert r["focal_source"] == "request" and r["focallength_px"] == 400.0 and npy(r["depth"]).dtype == np.float32 + r2 = client.post("/predict", json={"image": b64(SAMPLE), "f_px": 800.0, "output_format": "none"}).json() + assert r2["depth"] is None and abs(r2["stats_m"]["median"] / r["stats_m"]["median"] - 2) < 1e-4 + r3 = client.post("/predict", json={"image": b64(SAMPLE), "output_format": "png16", "png_scale": 100}).json() + assert r3["depth"]["format"] == "png16" and r3["depth"]["scale"] == 100.0 + # an image of another size: resized to the nearest-aspect bucket and back + small = np.full((300, 400, 3), 120, np.uint8) + small[150:] = 60 + r4 = client.post("/predict", json={"image": b64(png_bytes(small))}).json() + assert r4["resized"] and r4["bucket"] == [240, 320] and npy(r4["depth"]).shape == (300, 400) + + +def test_predict_png(client): + r = client.post("/predict_png?png_scale=1000", content=SAMPLE) + assert r.status_code == 200, r.text + assert r.headers["content-type"] == "image/png" + from PIL import Image + + im = np.asarray(Image.open(io.BytesIO(r.content))) + assert im.shape == (480, 640) and int(r.headers["x-infinite-pixels"]) == int((im == 0).sum()) + assert float(r.headers["x-focal-length-px"]) > 0 and json.loads(r.headers["x-stats-m"])["median"] > 0 + assert client.post("/predict_png", content=b"").status_code == 400 + assert client.post("/predict_png", content=b"garbage").status_code == 400 + assert client.post("/predict_png?f_px=-3", content=SAMPLE).status_code == 400 + assert client.post("/predict_png?colour=1", content=SAMPLE).status_code == 400 + + +def test_predict_video_modes(client): + g = golden("stream_buf_w4o1_n10__S") + frames = [b64(png_bytes(a)) for a in g["input_u8"].numpy()[:3]] + r = client.post("/predict_video", json={"frames": frames, "include_inverse_depth": True}) + assert r.status_code == 200, r.text + body = r.json() + assert body["frames"] == 3 and body["frame_indices"] == [0, 1, 2] and body["window"] == 2 + assert body["overlap"] == 1 and len(body["stats_m"]) == 3 and npy(body["depth"]).shape == (3, 240, 320) + model = server.app.state.dp2.model + api = list(model.infer_video(list(g["input_u8"].numpy()[:3]))) + inv = npy(body["inverse_depth"]).astype(np.float32) + want = np.stack([o.inverse_depth.numpy() for o in api]) + assert rel_err(inv, want) < 2e-3 # float16 encoding + # the same frames as a .npy clip, and as ONE clip (2 frames = the window) + buf = io.BytesIO() + np.save(buf, g["input_u8"].numpy()[:2]) + r2 = client.post("/predict_video", json={"clip": {"format": "npy", "data": b64(buf.getvalue())}, + "mode": "clip", "f_px": 300.0}).json() + assert r2["frames"] == 2 and r2["focal_source"] == "request" and r2["window"] == 2 + r3 = client.post("/predict_video", json={"frames": frames, "mode": "clip"}) + assert r3.status_code == 400 and "window" in r3.json()["detail"] # 3 frames: longer than the window + + +def test_video_stream_across_requests(client): + g = golden("stream_buf_w4o1_n10__S") + frames = [b64(png_bytes(a)) for a in g["input_u8"].numpy()[:5]] + r1 = client.post("/predict_video", json={"frames": frames[:1], "stream": {"id": "cam0"}}).json() + assert r1["frames"] == 0 and r1["stream"]["pending"] == 1 and r1["depth"] is None + busy = client.post("/predict_video", json={"frames": frames[:1], "stream": {"id": "cam1"}}) + assert busy.status_code == 429 # DEPTHPRO2_MAX_STREAMS=1 + bad = client.post("/predict_video", json={"frames": frames[:1], "stream": {"id": "cam0"}, "f_px": 3.0}) + assert bad.status_code == 400 + r2 = client.post("/predict_video", json={"frames": frames[1:3], "stream": {"id": "cam0"}}).json() + r3 = client.post("/predict_video", json={"frames": frames[3:], "stream": {"id": "cam0", "end": True}}).json() + got = r1["frame_indices"] + r2["frame_indices"] + r3["frame_indices"] + assert got == [0, 1, 2, 3, 4] and r3["stream"]["ended"] and r3["stream"]["pending"] == 0 + assert server.app.state.dp2.streams == {} + whole = client.post("/predict_video", json={"frames": frames, "output_format": "npy32", + "include_inverse_depth": True}).json() + parts = [client.post("/predict_video", json={"frames": frames[a:b], "stream": {"id": "x", "end": b == 5}, + "output_format": "npy32", "include_inverse_depth": True}).json() + for a, b in ((0, 2), (2, 5))] + inv_parts = np.concatenate([npy(p["inverse_depth"]) for p in parts if p["frames"]]) + assert np.array_equal(inv_parts, npy(whole["inverse_depth"])) # same clips, same cross-fade + + +def test_errors(client): + good = {"image": b64(SAMPLE)} + cases = [ + ("/predict", {"image": "not base64!"}, 400), ("/predict", {"image": b64(b"hello")}, 400), + ("/predict", dict(good, f_px=-1.0), 400), ("/predict", dict(good, f_px=0), 400), + ("/predict", dict(good, png_scale=0), 400), ("/predict", dict(good, temperature=1), 422), + ("/predict", dict(good, output_format="jpeg"), 422), ("/predict", {}, 422), ("/predict", {"image": 3}, 422), + ("/predict_video", {"frames": [b64(SAMPLE), b64(png_bytes(np.zeros((32, 32, 3), np.uint8)))]}, 400), + ("/predict_video", {"frames": [b64(SAMPLE)] * 9}, 400), ("/predict_video", {}, 400), + ("/predict_video", {"frames": []}, 400), + ("/predict_video", {"frames": [b64(SAMPLE)], "mode": "live"}, 422), + ("/predict_video", {"frames": [b64(SAMPLE)], "window": 3}, 400), + ("/predict_video", {"frames": [b64(SAMPLE)], "mode": "clip", "overlap": 0}, 400), + ("/predict_video", {"clip": {"format": "npy", "data": b64(b"xx")}}, 400), + ("/predict_video", {"frames": [b64(SAMPLE)], "stream": {"id": "s", "end": True}, "mode": "clip"}, 400), + ] + for route, payload, want in cases: + r = client.post(route, json=payload) + assert r.status_code == want, (route, list(payload), r.status_code, r.text[:200]) + if want == 400: + assert r.json()["detail"] + + +def test_unbuffered_stream_over_http(client): + g = golden("stream_unbuf_w4_n6__S") + frames = [b64(png_bytes(a)) for a in g["input_u8"].numpy()[:3]] + info = client.get("/info").json()["configuration"] + assert info["video_modes"] == ["buffered", "unbuffered"] and info["kv_streams"] == 1 + assert info["kv_cache"]["caches"] == 2 # one per bucket + got = [] + for k, f in enumerate(frames): + r = client.post("/predict_video", json={"frames": [f], "mode": "unbuffered", "f_px": 300.0 if k == 0 else None, + "include_inverse_depth": True, "stream": {"id": "u", "end": k == 2}}) + assert r.status_code == 200, r.text + body = r.json() + assert body["frame_indices"] == [k] and body["stream"]["mode"] == "unbuffered" # returned at once + got.append(npy(body["inverse_depth"])[0].astype(np.float32)) + if k == 0: + busy = client.post("/predict_video", json={"frames": [f], "mode": "unbuffered", "stream": {"id": "u2"}}) + assert busy.status_code == 429 # DEPTHPRO2_MAX_STREAMS=1 here (KV_STREAMS=1 as well) + whole = client.post("/predict_video", json={"frames": [f], "mode": "unbuffered"}) + assert whole.status_code == 429 and "KV_STREAMS" in whole.json()["detail"] # needs a cache too + wrong = client.post("/predict_video", json={"frames": [f], "stream": {"id": "u"}}) + assert wrong.status_code == 400 # a buffered request on the unbuffered stream + # the same frames through the API in one unbuffered video (window 2 = the server's window) + model = server.app.state.dp2.model + api = [o.inverse_depth.numpy() for o in model.infer_video(list(g["input_u8"].numpy()[:3]), mode="unbuffered", + f_px=300.0)] + assert rel_err(np.stack(got), np.stack(api)) < 2e-3 + assert model._kv_open == 0 and server.app.state.dp2.streams == {} + + +def test_buffered_only_server_refuses_unbuffered(monkeypatch): + with client_with(monkeypatch, DEPTHPRO2_VIDEO_MODES="buffered") as c: + assert c.get("/config").json()["configuration"]["video_modes"] == ["buffered"] + r = c.post("/predict_video", json={"frames": [b64(SAMPLE)], "mode": "unbuffered"}) + assert r.status_code == 400 and "not enabled" in r.json()["detail"] + + +def test_body_limit(monkeypatch): + with client_with(monkeypatch, DEPTHPRO2_MAX_BODY_MB="1") as c: + r = c.post("/predict", json={"image": "A" * (2 << 20)}) + assert r.status_code == 400 and "MAX_BODY_MB" in r.json()["detail"] + + +def test_device_failure_is_500_and_starting_is_503(monkeypatch): + def failing(cfg): + m = cpu_factory(cfg) + + def boom(x): + raise RuntimeError("device hung") + + m.engine.inverse_depth = boom + return m + + with client_with(monkeypatch, failing) as c: + r = c.post("/predict", json={"image": b64(SAMPLE)}) + assert r.status_code == 500 and "RuntimeError: device hung" in r.json()["detail"] + st = server.app.state.dp2 + st.ready = False + assert c.post("/predict", json={"image": b64(SAMPLE)}).status_code == 503 + assert c.get("/health").json()["status"] == "starting" + st.ready = True + + +def test_startup_refuses_a_bad_configuration(monkeypatch): + with pytest.raises(RuntimeError, match="DEPTHPRO2_WINDOW"): + with client_with(monkeypatch, DEPTHPRO2_WINDOW="99"): + pass + assert server.app.state.dp2.error is None # restored by client_with + + +def test_shutdown_closes_the_model(monkeypatch): + with client_with(monkeypatch) as c: + m = server.app.state.dp2.model + r = c.post("/predict_video", json={"frames": [b64(SAMPLE)], "stream": {"id": "open"}}) + assert r.status_code == 200, r.text + st = server.app.state.dp2 + assert st.streams # the open stream is closed at shutdown too + assert m.closed and server.app.state.dp2.model is not m + + +def _free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def test_smoke_test_passes_over_http(monkeypatch, tmp_path): + """The stdlib smoke test (what container_smoke.sh runs) against the app served by uvicorn on the CPU engine.""" + need_weights("S") + uvicorn = pytest.importorskip("uvicorn") + import importlib.util + + for k, v in dict(ENV, DEPTHPRO2_RESOLUTIONS="vga", DEPTHPRO2_MAX_STREAMS="2").items(): + monkeypatch.setenv(k, v) + st = server.app.state.dp2 + old = (st.model_factory, st.model, st.config, st.ready, st.error) + st.model_factory, st.model, st.config, st.ready, st.error = (lambda cfg: cpu_factory(cfg, warmup=True)), None, \ + None, False, None + port = _free_port() + srv = uvicorn.Server(uvicorn.Config(server.app, host="127.0.0.1", port=port, log_level="warning", lifespan="on")) + t = threading.Thread(target=srv.run, daemon=True) + t.start() + try: + spec = importlib.util.spec_from_file_location("dp2_smoke", SMOKE) + smoke = importlib.util.module_from_spec(spec) + spec.loader.exec_module(smoke) + out = tmp_path / "smoke.json" + # a staged-manifest stand-in pinning profile s (what tt-model writes: container.serve(.env), serve_profiles) + man = tmp_path / "tt_kernel_manifest.json" + from tt_depthpro2 import config as C + + man.write_text(json.dumps({ + "name": "depthpro2", "weights": {"repo": "apple/DepthPro2-focal", "revision": C.WEIGHTS["focal"][1]}, + "auxiliary_weights": [{"repo": r, "revision": v} for k, (r, v) in C.WEIGHTS.items() if k != "focal"], + "container": {"serve": {"env": {"DEPTHPRO2_DISPATCH": "eth", "DEPTHPRO2_NUM_CQS": "1", + "DEPTHPRO2_RESOLUTIONS": "vga", "DEPTHPRO2_WINDOW": "2", + "DEPTHPRO2_OVERLAP": "1"}}, + "serve_profiles": [{"name": "s", "env": {"DEPTHPRO2_SIZE": "S"}}], "default_profile": "s"}})) + rc = smoke.main(["--url", f"http://127.0.0.1:{port}", "--wait", "300", "--out", str(out), + "--manifest", str(man)]) + assert rc == 0 + body = json.loads(out.read_text()) + assert body["size"] == "S" and "<" in body["depth"]["data"] # arrays elided + finally: + srv.should_exit = True + t.join(timeout=60) + st.model_factory, st.model, st.config, st.ready, st.error = old diff --git a/code/tt_depthpro2/tests/test_host_streaming.py b/code/tt_depthpro2/tests/test_host_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..071b8fbe38391db8ddacef252e50852a4ca70c51 --- /dev/null +++ b/code/tt_depthpro2/tests/test_host_streaming.py @@ -0,0 +1,254 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Host tests of the video streaming (no device): the buffered ``DepthStream`` semantics on synthetic clips (which +frames each clip predicts, the cross-fade weights, the flush of the tail with and without an overlap, the focal +length over the frames so far), ``plan_buffered_clips`` against the stream, the unbuffered mode's requirements, and +-- with the weights and goldens -- the API's buffered and unbuffered video on the CPU engine against Apple's float32 +``stream_buf_w4o1_n10`` / ``stream_unbuf_w4_n6`` goldens. + + PYTHONPATH=/research/packaging/scripts:code TT_VISIBLE_DEVICES=none \ + python -m pytest -p fake_ttnn_plugin code/tt_depthpro2/tests/test_host_streaming.py +""" +from __future__ import annotations + +import random + +import pytest +import torch + +from tt_depthpro2.api import plan_buffered_clips +from tt_depthpro2.streaming import DepthStream, blend_weights +from tt_depthpro2.tests.host_helpers import cpu_model, depth_rel_err_valid, golden, pcc, rel_err + + +class Spy: + """A fake clip predictor: frame k (a 3 x 2 x 2 tensor filled with k) predicts k + 1000 * (its clip number).""" + + def __init__(self): + self.clips = [] + + def __call__(self, clip): + self.clips.append([int(v) for v in clip[:, 0, 0, 0].tolist()]) + return clip[:, 0] + 1000.0 * len(self.clips) + + +def frame(k): + return torch.full((3, 2, 2), float(k)) + + +def run(n, window, overlap, **kw): + spy = Spy() + s = DepthStream(spy, window=window, overlap=overlap, **kw) + out = [] + for k in range(n): + out += s.step(frame(k)) + out += s.flush() + return spy, out, s + + +def test_blend_weights(): + assert blend_weights(1, torch.zeros(1)).flatten().tolist() == [0.5] + assert torch.allclose(blend_weights(3, torch.zeros(1)).flatten(), torch.tensor([0.75, 0.5, 0.25])) + + +def test_buffered_w4_o1_n10(): + spy, out, _ = run(10, 4, 1) + assert spy.clips == [[0, 1, 2, 3], [3, 4, 5, 6], [6, 7, 8, 9]] + assert [p.index for p in out] == list(range(10)) + vals = [float(p.inverse_depth[0, 0]) for p in out] + want = [1000, 1001, 1002, 0.5 * 1003 + 0.5 * 2003, 2004, 2005, 0.5 * 2006 + 0.5 * 3006, 3007, 3008, 3009] + assert vals == pytest.approx(want) + + +def test_buffered_overlap2_crossfade(): + spy, out, _ = run(6, 4, 2) + # clip 1: 0..3 (returns 0, 1; holds 2, 3); flush: pulled back to a full window 2..5 + assert spy.clips == [[0, 1, 2, 3], [2, 3, 4, 5]] + vals = [float(p.inverse_depth[0, 0]) for p in out] + w = [2 / 3, 1 / 3] + want = [1000, 1001, w[0] * 1002 + (1 - w[0]) * 2002, w[1] * 1003 + (1 - w[1]) * 2003, 2004, 2005] + assert vals == pytest.approx(want) + + +def test_flush_tails(): + spy, out, _ = run(5, 4, 1) # tail pulled back over frames already returned (1..4); 3 cross-faded, 4 new + assert spy.clips == [[0, 1, 2, 3], [1, 2, 3, 4]] and [p.index for p in out] == [0, 1, 2, 3, 4] + spy, out, _ = run(6, 4, 0) # no overlap: the tail is just the new frames + assert spy.clips == [[0, 1, 2, 3], [4, 5]] and len(out) == 6 + spy, out, _ = run(3, 4, 2) # shorter than the window: one short clip at flush + assert spy.clips == [[0, 1, 2]] and len(out) == 3 + spy, out, _ = run(8, 4, 1) # one new frame at flush: a full window pulled back over 4..7 + assert spy.clips == [[0, 1, 2, 3], [3, 4, 5, 6], [4, 5, 6, 7]] and [p.index for p in out] == list(range(8)) + spy, out, _ = run(7, 4, 1) # nothing new at flush: the held frame is returned without another clip + assert spy.clips == [[0, 1, 2, 3], [3, 4, 5, 6]] and [p.index for p in out] == list(range(7)) + assert float(out[-1].inverse_depth[0, 0]) == 2006.0 + spy, out, _ = run(0, 4, 1) + assert spy.clips == [] and out == [] + + +def test_window_one_and_returns_in_order(): + spy, out, _ = run(5, 1, 0) + assert spy.clips == [[k] for k in range(5)] and [p.index for p in out] == list(range(5)) + + +def test_plan_matches_the_stream(): + rng = random.Random(0) + for _ in range(200): + w = rng.randint(1, 16) + o = rng.randint(0, w - 1) + n = rng.randint(0, 50) + spy, out, _ = run(n, w, o) + assert [len(c) for c in spy.clips] == plan_buffered_clips(n, w, o), (n, w, o) + assert [p.index for p in out] == list(range(n)) + + +def test_step_after_flush_continues(): + spy = Spy() + s = DepthStream(spy, window=4, overlap=1) + out = [] + for k in range(5): + out += s.step(frame(k)) + out += s.flush() + for k in range(5, 9): + out += s.step(frame(k)) + out += s.flush() + assert [p.index for p in out] == list(range(9)) + + +def test_focal_over_frames_so_far(): + calls = [] + + def fov(clip): + calls.append(clip.shape[0]) + return torch.stack([clip[:, 0, 0, 0] + 60.0, clip[:, 0, 0, 0] + 45.0], dim=1) + + def focal(fov_deg, h, w): + return fov_deg[:, 1].median() + + spy = Spy() + s = DepthStream(spy, window=4, overlap=1, fov_deg=fov, focal_from_fov=focal) + out = [] + for k in range(10): + out += s.step(frame(k)) + out += s.flush() + assert calls == [4] # the first clip's frames; fixed once a window of estimates is in + # clip 1: median of vfov 45..48 (lower median) -> 46; fixed once 4 estimates are in + assert float(out[0].f_px) == 46.0 and float(out[-1].f_px) == 46.0 and float(s.f_px) == 46.0 + s2 = DepthStream(Spy(), window=4, overlap=1, f_px=123.0, fov_deg=fov, focal_from_fov=focal) + calls.clear() + got = [p for k in range(4) for p in s2.step(frame(k))] + assert calls == [] and all(float(p.f_px) == 123.0 for p in got) + + +def test_errors(): + with pytest.raises(ValueError): + DepthStream(Spy(), window=4, overlap=4) + with pytest.raises(ValueError): + DepthStream(Spy(), window=0, overlap=0) + with pytest.raises(ValueError): + DepthStream(Spy(), window=4, overlap=1, mode="live") + with pytest.raises(NotImplementedError): + DepthStream(Spy(), window=4, overlap=0, mode="unbuffered") + s = DepthStream(Spy(), window=4, overlap=1) + s.step(frame(0)) + with pytest.raises(ValueError): + s.step(torch.zeros(3, 4, 4)) + with pytest.raises(ValueError): + s.step(torch.zeros(1, 3, 2, 2)) + s.close() + with pytest.raises(RuntimeError): + s.step(frame(1)) + + +def test_unbuffered_with_a_cache(): + opened = [] + + def step(clip, cache): + cache.append(int(clip[0, 0, 0, 0])) + return clip[:, 0] + 10.0 * len(cache) + + def open_cache(): + opened.append([]) + return opened[-1] + + s = DepthStream(Spy(), window=3, overlap=2, mode="unbuffered", predict_step=step, open_cache=open_cache) + out = [] + for k in range(5): + got = s.step(frame(k)) + assert [p.index for p in got] == [k] # returned at once + out += got + assert s.flush() == [] and opened == [[0, 1, 2, 3, 4]] + assert [float(p.inverse_depth[0, 0]) for p in out] == [10, 21, 32, 43, 54] + + +# ---------------------------------------------------------------------------------------------- Apple's goldens + + +def test_buffered_video_matches_the_official_golden(): + g = golden("stream_buf_w4o1_n10__S") + m = cpu_model("S", resolutions="240x320", window=4, overlap=1, clip_lengths="all") + outs = list(m.infer_video(list(g["input_u8"].numpy()))) + assert [o.frame_index for o in outs] == list(range(10)) + inv = torch.stack([o.inverse_depth for o in outs]) + depth = torch.stack([o.depth for o in outs]) + assert rel_err(inv, g["inverse_depth"]) < 1e-5 and pcc(inv, g["inverse_depth"]) > 0.999999 + # the focal length comes from the reference FOV (within 1e-4 of Apple's float32 here) + f_rel = abs(outs[0].focallength_px - float(g["focallength_px"])) / float(g["focallength_px"]) + assert f_rel < 1e-3 + # depth where it is well defined (see depth_rel_err_valid): <= 100 x the inverse-depth bound (1e-5) + f_rel + assert depth_rel_err_valid(depth, g["depth"], g["inverse_depth"]) < 1e-3 + f_rel + 1e-4 # + 1e-4 margin + assert all(o.focal_source == "fov" and o.focallength_px == outs[0].focallength_px for o in outs) + + +def test_unbuffered_video_matches_the_official_golden(): + g = golden("stream_unbuf_w4_n6__S") + m = cpu_model("S", resolutions="240x320", window=4, overlap=1, clip_lengths="all", + video_modes="buffered,unbuffered") + assert m.supports_unbuffered + outs = list(m.infer_video(list(g["input_u8"].numpy()), mode="unbuffered")) + inv = torch.stack([o.inverse_depth for o in outs]) + assert [o.frame_index for o in outs] == list(range(6)) + assert rel_err(inv, g["inverse_depth"]) < 1e-5 + f_rel = abs(outs[0].focallength_px - float(g["focallength_px"])) / float(g["focallength_px"]) + assert f_rel < 1e-3 + # depth where it is well defined: near the sky (inverse depth ~0) the depth of the float32 CPU engine moves with + # the torch thread count (5 % at 4 threads, while the inverse depth stays within 1e-5); on the valid pixels it is + # bounded by 100 x the inverse-depth bound (1e-5) + the focal length's error + depth = torch.stack([o.depth for o in outs]) + assert depth_rel_err_valid(depth, g["depth"], g["inverse_depth"]) < 1e-3 + f_rel + 1e-4 # + 1e-4 margin + + +def test_buffered_video_given_f_px_and_resized_frames(): + g = golden("stream_buf_w4o1_n10__S") + m = cpu_model("S", resolutions="240x320", window=4, overlap=1, clip_lengths="all") + u8 = g["input_u8"].numpy() + outs = list(m.infer_video(list(u8), f_px=300.0)) + assert all(o.focal_source == "request" and o.focallength_px == 300.0 for o in outs) + inv = torch.stack([o.inverse_depth for o in outs]) + assert rel_err(inv, g["inverse_depth"]) < 1e-5 + assert rel_err(torch.stack([o.depth for o in outs]), 300.0 / (320 * g["inverse_depth"])) < 1e-5 + # frames twice the bucket size: resized to the bucket and back; the focal length scales with the width + big = u8.repeat(2, axis=1).repeat(2, axis=2) + outs2 = list(m.infer_video(list(big))) + assert outs2[0].inverse_depth.shape == (480, 640) and outs2[0].resized + f2 = outs2[0].focallength_px + assert abs(f2 / (2 * float(g["focallength_px"])) - 1) < 0.02 + small = torch.nn.functional.avg_pool2d(torch.stack([o.inverse_depth for o in outs2])[:, None], 2)[:, 0] + assert pcc(small, g["inverse_depth"]) > 0.995 + + +def test_live_stream_session_matches_infer_video(): + g = golden("stream_buf_w4o1_n10__S") + m = cpu_model("S", resolutions="240x320", window=4, overlap=1, clip_lengths="all") + u8 = g["input_u8"].numpy() + s = m.stream() + got = [] + for k in range(10): + got += s.step(u8[k]) + if k < 3: + assert got == [] # nothing until a window is full + got += s.flush() + s.close() + inv = torch.stack([o.inverse_depth for o in got]) + assert [o.frame_index for o in got] == list(range(10)) + assert rel_err(inv, g["inverse_depth"]) < 1e-5 # inverse depth does not depend on the focal length + assert s.focallength_px is not None and all(o.focallength_px for o in got) diff --git a/code/tt_depthpro2/tt/__init__.py b/code/tt_depthpro2/tt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5152971e5ecadc54b50610a05f2b71f8c9366d89 --- /dev/null +++ b/code/tt_depthpro2/tt/__init__.py @@ -0,0 +1,75 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Device side of the DepthPro2 port. + +Stage engines (``ttnn_enc`` / ``ttnn_dec`` / ``ttnn_fov`` and the megakernel ``mk_*`` modules) share one contract +(research/depthpro2/SPEC.md §3): + +* every engine module exports ``Engine``; ``Engine(device, weights, shape)`` uploads the per-shape constants and + compiles nothing that has to happen after a trace capture; ``Engine.run(inputs) -> outputs`` only enqueues device + work (trace-capturable, no host sync); +* an engine class MAY define ``Engine.prepare_weights(device, host_weights, size) -> obj`` (staticmethod): ``tt/model.py`` + calls it once per stage and passes ``obj`` as ``weights`` to every per-shape engine (weights are uploaded once and + shared by all buckets / clip lengths); without it the engine receives the host dict (name -> float32 torch tensor); +* ``shape`` is a :class:`StageShape`; +* an ENC engine MAY support a runtime valid-frame count: ``Engine.supports_valid_frames = True`` and + ``Engine.set_valid_frames(n)`` (host call before a run / trace replay; writes persistent device tensors only): the + T-frame program then processes frames ``[0, n)`` as an n-frame clip (frames ``>= n`` excluded from every + cross-frame block's joint keys and pooled-prefix mean; their outputs don't-care). Contract: BASELINE.md §9.2. + +Token-grid geometry for a padded frame ``Hp x Wp`` (multiples of 32): ``gh = Hp / 16``, ``gw = Wp / 16``, +``N = gh * gw`` patches, ``Np = ceil32(N)``. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +PATCH = 16 +NUM_PREFIX = 5 +TILE = 32 + + +def ceil32(n: int) -> int: + return (n + TILE - 1) // TILE * TILE + + +@dataclass(frozen=True) +class StageShape: + """One compiled configuration: ``frames`` (T) frames of ``hp x wp`` padded pixels (multiples of 32).""" + + frames: int + hp: int + wp: int + + def __post_init__(self): + if self.hp % 32 or self.wp % 32 or self.hp <= 0 or self.wp <= 0: + raise ValueError(f"padded size must be positive multiples of 32, got {self.hp}x{self.wp}") + if not 1 <= self.frames <= 64: + raise ValueError(f"frames must be in 1..64, got {self.frames}") + + @property + def gh(self) -> int: + return self.hp // PATCH + + @property + def gw(self) -> int: + return self.wp // PATCH + + @property + def n(self) -> int: + """Patch tokens per frame.""" + return self.gh * self.gw + + @property + def np_(self) -> int: + """Patch rows per frame in the stage-contract layouts (``ceil32(N)``).""" + return ceil32(self.n) + + @property + def lp(self) -> int: + """Rows per frame of the ttnn encoder's token tensor: [N patches ; 5 prefix ; pad] = ``ceil32(N + 5)``.""" + return ceil32(self.n + NUM_PREFIX) + + @property + def key(self) -> str: + return f"T{self.frames}_{self.hp}x{self.wp}" diff --git a/code/tt_depthpro2/tt/mk_dec/__init__.py b/code/tt_depthpro2/tt/mk_dec/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c3536f2e4b775d609d6e14f9db9e8c8adc67e8d0 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_dec/__init__.py @@ -0,0 +1,12 @@ +# SPDX-License-Identifier: Apache-2.0 +"""DepthPro2 DEC megakernel (one persistent generic_op for reassemble + DPT decoder + head of all T frames). + +``Engine`` is the stage-engine entry point ``tt/model.py`` loads for ``dec=mk`` (``tt.mk_dec.Engine``).""" + + +def __getattr__(name): + if name in ("Engine", "MkDec", "MkDecWeights"): + from . import program + + return getattr(program, name) + raise AttributeError(name) diff --git a/code/tt_depthpro2/tt/mk_dec/kernels/md_brisc.cpp b/code/tt_depthpro2/tt/mk_dec/kernels/md_brisc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b280cb915915c6dc897b092afaf17938533a9af2 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_dec/kernels/md_brisc.cpp @@ -0,0 +1,595 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// DepthPro2 DEC megakernel, BRISC (NoC 1): boot + global hub barriers, the plan table and constants, every DRAM +// read of a unit's inputs (ROW_MAJOR bands of the input / residual maps, HC selector tiles, RA tap tiles) and every +// DRAM write of its outputs (ROW_MAJOR map runs incl. depth-to-space, the float32 inverse depth tiles). +// Map storage (plan.py MapG): storage pixel of (y, x) = B0 + y * WP + x, pages of 32 storage pixels x C channels; +// pads / guard rows are zero and never written. +#include "md_dm.hpp" + +using namespace mdx; + +namespace { + +constexpr auto acc_dram = TensorAccessorArgs(); +constexpr uint32_t OUT_BLK = 8; // CB_OUT pages per output block (the TRISC pushes whole 8-page blocks) +#define MD_NOINL __attribute__((noinline)) + +Plan pl; +uint32_t me_x, me_y, role, nall, hubx, huby, ax0, ay0, ax1, ay1; +uint32_t gen_bar = 0; + +FORCE_INLINE auto dram(uint32_t addr, uint32_t page_bytes) { return TensorAccessor(acc_dram, addr, page_bytes); } + +MD_NOINL void wait_ge(uint32_t w, uint32_t v) { + WAYPOINT("BWGE"); + spin_ge(w, v); +} + +void boot_barrier() { + const uint32_t sem_boot = get_semaphore(0); + const uint32_t sem_go = get_semaphore(1); + noc_semaphore_inc(get_noc_addr(hubx, huby, sem_boot), 1); + at_bar(); + if (role & R_HUB) { + volatile tt_l1_ptr uint32_t* b = reinterpret_cast(sem_boot); + WAYPOINT("BOOT"); + uint32_t it = 0; + while (true) { + invalidate_l1_cache(); + if (*b >= nall) { + break; + } + if (++it > g_spin) { + abort_note(AB_SYNC, 998); + break; + } + } + volatile tt_l1_ptr uint32_t* go = reinterpret_cast(sem_go); + *go = 1; + noc_semaphore_set_multicast_loopback_src(sem_go, mcast_addr(ax0, ay0, ax1, ay1, sem_go), nall); + wr_flush(); + } + wait_go(sem_go); +} + +// global barrier: every write of this core landed, then the hub counts arrivals and multicasts the generation +MD_NOINL void barrier() { + ++gen_bar; + wr_bar(); + noc_semaphore_inc(get_noc_addr(hubx, huby, sync_addr(W_BCNT)), 1); + at_bar(); + if (role & R_HUB) { + wait_ge(W_BCNT, gen_bar * nall); + const uint32_t srcw = sync_addr(W_SRC); + *reinterpret_cast(srcw) = gen_bar; + noc_semaphore_set_multicast_loopback_src(srcw, mcast_addr(ax0, ay0, ax1, ay1, sync_addr(W_BAR)), nall); + wr_flush(); + } + wait_ge(W_BAR, gen_bar); +} + +// ------------------------------------------------------------------ map access +// DRAM request discipline (Blackhole SYS-1419, mk_enc's never-hung pattern): every DRAM request of the map / output +// traffic is >= 2 KB. Map rows start on 32-pixel pages (plan.py MapG), so a unit's tile columns are whole pages; the +// C3 / HC band halo pixels come from 2 KB edge chunks; outputs are staged in L1 (CB_RES memory) and leave as whole +// pages (C3, UP, RA) or 2 KB fp32 face pairs (HC). Gathers into the staging area are local L1 -> L1 NoC copies. +struct MapA { + uint32_t addr, C, wp, b0, fpix, bpx; // bpx = bytes per storage pixel +}; +FORCE_INLINE MapA map_of(uint32_t m) { + MapA a; + a.addr = ca(pl.mf(m, M_ARG)); + a.C = pl.mf(m, M_C); + a.wp = pl.mf(m, M_WP); + a.b0 = pl.mf(m, M_B0); + a.fpix = pl.mf(m, M_FPG) * 32; + a.bpx = a.C * 2; + return a; +} +// storage pixel of (f, y, x) (y, x may be -1) +FORCE_INLINE uint32_t spx(const MapA& a, uint32_t f, int32_t y, int32_t x) { + return f * a.fpix + (uint32_t)((int32_t)a.b0 + y * (int32_t)a.wp + x); +} +// one DRAM read of npx storage pixels from g (the run stays inside one 32-pixel page) +FORCE_INLINE void rd_run(const MapA& a, uint32_t g, uint32_t npx, uint32_t dst) { + noc_async_read(dram(a.addr, 32 * a.bpx).get_noc_addr(g >> 5, (g & 31) * a.bpx), dst, npx * a.bpx); +} +// read n storage pixels from a page-aligned g (whole pages) to dst +MD_NOINL void read_px(const MapA& a, uint32_t g, uint32_t n, uint32_t dst) { + while (n) { + const uint32_t off = g & 31; + const uint32_t cnt = 32 - off < n ? 32 - off : n; + rd_run(a, g, cnt, dst); + dst += cnt * a.bpx; + g += cnt; + n -= cnt; + } +} +// one whole page (32 pixels x C) from L1 src to the page-aligned storage pixel g +FORCE_INLINE void wr_page(const MapA& a, uint32_t g, uint32_t src) { + noc_async_write(src, dram(a.addr, 32 * a.bpx).get_noc_addr(g >> 5, 0), 32 * a.bpx); +} +FORCE_INLINE uint32_t stage_base() { return cb_base(CB_RES); } +MD_NOINL void zero_l1(uint32_t addr, uint32_t bytes) { + volatile tt_l1_ptr uint32_t* p = reinterpret_cast(addr); + for (uint32_t i = 0; i < (bytes >> 2); ++i) { + p[i] = 0; + } +} +// local L1 -> L1 copy through the NoC (gathers into the staging area; no DRAM traffic) +FORCE_INLINE void lcopy(uint32_t src, uint32_t dst, uint32_t bytes) { noc_async_write(src, get_noc_addr(dst), bytes); } + +// ------------------------------------------------------------------ units +struct Lay { + uint32_t l, op, s, nbw, nbi, n, bh, bw, ct, kc, flags, nres, ho, wo, kxo, bandp, boff, kpx; + uint32_t src, dst, res0, res1; +}; +FORCE_INLINE void lay_of(uint32_t l, Lay& L) { + L.l = l; + L.op = pl.lf(l, L_OP); + L.s = pl.lf(l, L_S); + L.nbw = pl.lf(l, L_NBW); + L.nbi = pl.lf(l, L_NBI); + L.n = pl.lf(l, L_N); + L.bh = pl.lf(l, L_BH); + L.bw = pl.lf(l, L_BW); + L.ct = pl.lf(l, L_CT); + L.kc = pl.lf(l, L_KC); + L.flags = pl.lf(l, L_FLAGS); + L.nres = pl.lf(l, L_NRES); + L.ho = pl.lf(l, L_HO); + L.wo = pl.lf(l, L_WO); + L.kxo = pl.lf(l, L_KXO); + L.bandp = pl.lf(l, L_BANDP); + L.boff = pl.lf(l, L_BOFF); + L.kpx = pl.lf(l, L_KPX); + L.src = pl.lf(l, L_SRC); + L.dst = pl.lf(l, L_DST); + L.res0 = pl.lf(l, L_RES0); + L.res1 = pl.lf(l, L_RES1); +} + +// C3 / HC / UP band of unit un -> CB_BAND (one page) +MD_NOINL void load_band(const Lay& L, const Unit& un) { + const MapA a = map_of(L.src); + cbr_back(CB_BAND, 1); + const uint32_t dst = get_write_ptr(CB_BAND); + if (L.op == OP_UP) { + for (uint32_t j = 0; j < un.bh; ++j) { + read_px(a, spx(a, un.f, un.y0 + j, 32 * un.kx0), 32 * un.bw, dst + j * L.bandp); + } + } else { + // row j: [kpx - 1 slack px][x0 = s 32 kx0 - 1][s 32 bw px (whole pages)][s == 1: x0 + 32 bw + 1 .. + kpx - 1] + const uint32_t s = L.s, kpx = L.kpx, pxb = a.bpx; + const uint32_t rows = s * (un.bh - 1) + 3; + const uint32_t npx = s * 32 * un.bw; + for (uint32_t j = 0; j < rows; ++j) { + const uint32_t d = dst + L.boff + j * L.bandp; + const uint32_t g = spx(a, un.f, (int32_t)(s * un.y0 + j) - 1, (int32_t)(s * 32 * un.kx0)); + rd_run(a, g - kpx, kpx, d - (kpx - 1) * pxb); // left edge chunk: ends at x0 (last pixels of a page) + read_px(a, g, npx, d + pxb); + if (s == 1) { + rd_run(a, g + npx, kpx, d + (npx + 1) * pxb); // right edge chunk: starts at x0 + 32 bw + 1 + } + } + } + rd_bar(); + cb_push_back(CB_BAND, 1); +} + +// residual map m: the unit's output pixels (bh rows x 32 bw pixels, row pitch 32 BW pixels) -> CB_RES (one page) +MD_NOINL void load_res(const Lay& L, const Unit& un, uint32_t m) { + const MapA a = map_of(m); + cbr_back(CB_RES, 1); + const uint32_t dst = get_write_ptr(CB_RES); + const uint32_t pitch = 32 * L.bw * a.bpx; + for (uint32_t r = 0; r < un.bh; ++r) { + read_px(a, spx(a, un.f, un.y0 + r, 32 * un.kx0), 32 * un.bw, dst + r * pitch); + } + rd_bar(); + cb_push_back(CB_RES, 1); +} + +// HC bias selector tiles of the unit (row class x tile column) -> CB_SEL (r * bw + kx) +MD_NOINL void load_sel(const Lay& L, const Unit& un, uint32_t cap) { + const auto acc = dram(ca(K_SEL), T16); + const uint32_t kxh = pl.hdr(H_KX_HC); + cbr_back(CB_SEL, cap); + const uint32_t dst = get_write_ptr(CB_SEL); + for (uint32_t r = 0; r < un.bh; ++r) { + const uint32_t y = un.y0 + r; + const uint32_t ycls = y == 0 ? 0 : (y == L.ho - 1 ? 2 : 1); + for (uint32_t kx = 0; kx < un.bw; ++kx) { + noc_async_read_page(ycls * kxh + un.kx0 + kx, acc, dst + (r * un.bw + kx) * T16); + } + } + rd_bar(); + cb_push_back(CB_SEL, cap); +} + +// RA: tap tiles of token tiles [m0, m0 + mt) (K tiles each) -> CB_TAPA (mi * Kt + c) +MD_NOINL void load_taps(const Lay& L, uint32_t grp, uint32_t m0, uint32_t mt, uint32_t cap) { + const auto acc = dram(ca(K_TAP0 + L.src), T16); + const uint32_t pt = pl.hdr(H_PT), G = pl.hdr(H_G); + cbr_back(CB_TAPA, cap); + const uint32_t dst = get_write_ptr(CB_TAPA); + for (uint32_t mi = 0; mi < mt; ++mi) { + const uint32_t m = m0 + mi; + const uint32_t f = m / pt, p = m - f * pt; + const uint32_t row = (grp * G + f) * pt + p; + for (uint32_t c = 0; c < L.ct; ++c) { + noc_async_read_page(row * L.ct + c, acc, dst + (mi * L.ct + c) * T16); + } + } + rd_bar(); + cb_push_back(CB_TAPA, cap); +} + +// ------------------------------------------------------------------ outputs +// C3 with one n-block (whole pixels): output block (unit row r, tile kx) = 32 rows x C (ROW_MAJOR) = one page +MD_NOINL void write_c3(const Lay& L, const Unit& un, uint32_t r, uint32_t kx, uint32_t src) { + const MapA a = map_of(L.dst); + const uint32_t x0 = 32 * (un.kx0 + kx); + const uint32_t nv = L.wo - x0 < 32 ? L.wo - x0 : 32; + if (nv < 32) { + zero_l1(src + nv * a.bpx, (32 - nv) * a.bpx); // the pad columns stay zero + } + wr_page(a, spx(a, un.f, un.y0 + r, x0), src); +} + +// HC: fp32 tile (rows s = 2a + b, column i = pixel x0 + i) -> staging of tile column kx: output rows 2r + a (of the +// unit's 16), columns 2i + b (of 64) in the tile face layout of the two output tiles (2 x [16 x 16 | 16 x 16] fp32) +MD_NOINL void stage_hc(const Lay& L, const Unit& un, uint32_t r, uint32_t kx, uint32_t src, uint32_t st) { + const uint32_t x0 = 32 * (un.kx0 + kx); + const uint32_t nv = L.wo - x0 < 32 ? L.wo - x0 : 32; + invalidate_l1_cache(); + const volatile tt_l1_ptr uint32_t* t = reinterpret_cast(src); + volatile tt_l1_ptr uint32_t* o = reinterpret_cast(st); + for (uint32_t a = 0; a < 2; ++a) { + const uint32_t R = 2 * r + a; + for (uint32_t i = 0; i < nv; ++i) { + const uint32_t base = (i >> 4) * 256 + (i & 15); + for (uint32_t b = 0; b < 2; ++b) { + const uint32_t X = 2 * i + b; + o[(X >> 5) * 512 + ((X >> 4) & 1) * 256 + R * 16 + (X & 15)] = t[base + (2 * a + b) * 16]; + } + } + } +} +// HC unit done (8 input rows = 16 output rows, one half tile row): 2 KB face-pair writes per output tile +MD_NOINL void write_hc(const Lay& L, const Unit& un, uint32_t grp, uint32_t st) { + const uint32_t hp = pl.hdr(H_HP), wpx = pl.hdr(H_WP); + const uint32_t fr = grp * pl.hdr(H_G) + un.f; + const auto acc = dram(ca(K_OUT), T32); + const uint32_t Y0 = 2 * un.y0; // multiple of 16 (plan: HC units of 8 rows) + for (uint32_t kx = 0; kx < un.bw; ++kx) { + const uint32_t x0 = 32 * (un.kx0 + kx); + const uint32_t nv = L.wo - x0 < 32 ? L.wo - x0 : 32; + const uint32_t nt = (2 * nv + 31) / 32; + for (uint32_t t = 0; t < nt; ++t) { + const uint32_t X = 2 * x0 + 32 * t; + const uint32_t page = (fr * (hp >> 5) + (Y0 >> 5)) * (wpx >> 5) + (X >> 5); + noc_async_write(st + kx * 4096 + t * 2048, acc.get_noc_addr(page, ((Y0 & 31) >> 4) * 2048), 2048); + } + } + wr_flush(); +} + +// ------------------------------------------------------------------ layer +// C3 / HC / UP inputs of unit un +MD_NOINL void load_inputs(const Lay& L, const Unit& un) { + if (L.op == OP_UP) { + load_band(L, un); + return; + } + if (L.nres > 0) { + load_res(L, un, L.res0); + } + if (L.nres > 1) { + load_res(L, un, L.res1); + } + load_band(L, un); + if (L.op == OP_HC) { + load_sel(L, un, MD_SEL_CAP); + } +} + +// UP outputs of unit un, n-block group g. Block (nb, r, kx) = 32 input pixels x chn channels of output a-row a; per +// input pixel i its channels land contiguously at output pixel k i + b (a-row channel order (b, co)). Each (r, kx) +// stages its a-row (k * 32 output pixels x cout) and leaves as whole pages once the a-row's last n-block landed. +MD_NOINL void drain_up(const Lay& L, const Unit& un, uint32_t g) { + const MapA a = map_of(L.dst); + const uint32_t k = L.s, cob = a.bpx, chb = L.nbw * 64; + const uint32_t rowb = k * cob; // bytes of one input pixel's a-row (k output pixels x cout) + const uint32_t segb = 32 * rowb; // staging bytes of one (r, kx) + const uint32_t win = pl.mf(L.src, M_W); + const uint32_t st = stage_base(); + for (uint32_t nbi = 0; nbi < L.nbi; ++nbi) { + const uint32_t c0b = (g * L.nbi + nbi) * chb; // byte offset of the block in the output channel order + const uint32_t ar = c0b / rowb, cinb = c0b - ar * rowb; + for (uint32_t r = 0; r < un.bh; ++r) { + for (uint32_t kx = 0; kx < un.bw; ++kx) { + cbw_front(CB_OUT, OUT_BLK); + const uint32_t src = get_read_ptr(CB_OUT); + const uint32_t x0 = 32 * (un.kx0 + kx); + const uint32_t nv = win - x0 < 32 ? win - x0 : 32; + const uint32_t seg = st + (r * un.bw + kx) * segb; + if (chb == rowb) { + lcopy(src, seg, nv * chb); + } else { + for (uint32_t i = 0; i < nv; ++i) { + lcopy(src + i * chb, seg + i * rowb + cinb, chb); + } + } + wr_flush(); + cb_pop_front(CB_OUT, OUT_BLK); + } + } + if (cinb + chb == rowb) { // a-row ar complete for every (r, kx): whole output pages + wr_bar(); + for (uint32_t r = 0; r < un.bh; ++r) { + for (uint32_t kx = 0; kx < un.bw; ++kx) { + const uint32_t x0 = 32 * (un.kx0 + kx); + const uint32_t nv = win - x0 < 32 ? win - x0 : 32; + const uint32_t seg = st + (r * un.bw + kx) * segb; + if (nv < 32) { + zero_l1(seg + nv * rowb, (32 - nv) * rowb); + } + const uint32_t X0 = k * x0; + uint32_t np = (a.wp - X0) / 32; + if (np > k) { + np = k; + } + const uint32_t g0 = spx(a, un.f, k * (un.y0 + r) + ar, X0); + for (uint32_t p = 0; p < np; ++p) { + wr_page(a, g0 + 32 * p, seg + p * 32 * cob); + } + } + } + wr_flush(); + } + } +} + +// C3 / HC outputs of unit un (n-block group g) +MD_NOINL void drain(const Lay& L, const Unit& un, uint32_t g, uint32_t grp) { + if (L.op == OP_UP) { + drain_up(L, un, g); + return; + } + const uint32_t st = stage_base(); + if (L.op == OP_HC) { + for (uint32_t r = 0; r < un.bh; ++r) { + for (uint32_t kx = 0; kx < un.bw; ++kx) { + cbw_front(CB_HO, 1); + stage_hc(L, un, r, kx, get_read_ptr(CB_HO), st + kx * 4096); + cb_pop_front(CB_HO, 1); + } + } + write_hc(L, un, grp, st); + return; + } + if (L.nbi == 1) { // one n-block = whole pixels: each block is one page + for (uint32_t r = 0; r < un.bh; ++r) { + for (uint32_t kx = 0; kx < un.bw; ++kx) { + cbw_front(CB_OUT, OUT_BLK); + write_c3(L, un, r, kx, get_read_ptr(CB_OUT)); + wr_flush(); + cb_pop_front(CB_OUT, OUT_BLK); + } + } + return; + } + // several n-blocks on this core (nbo == 1): gather whole pixels, then one page per (r, kx) + const MapA a = map_of(L.dst); + const uint32_t chb = L.nbw * 64; + for (uint32_t nbi = 0; nbi < L.nbi; ++nbi) { + for (uint32_t r = 0; r < un.bh; ++r) { + for (uint32_t kx = 0; kx < un.bw; ++kx) { + cbw_front(CB_OUT, OUT_BLK); + const uint32_t src = get_read_ptr(CB_OUT); + const uint32_t seg = st + (r * un.bw + kx) * 32 * a.bpx; + for (uint32_t i = 0; i < 32; ++i) { + lcopy(src + i * chb, seg + i * a.bpx + nbi * chb, chb); + } + wr_flush(); + cb_pop_front(CB_OUT, OUT_BLK); + } + } + } + wr_bar(); + for (uint32_t r = 0; r < un.bh; ++r) { + for (uint32_t kx = 0; kx < un.bw; ++kx) { + const uint32_t x0 = 32 * (un.kx0 + kx); + const uint32_t nv = L.wo - x0 < 32 ? L.wo - x0 : 32; + const uint32_t seg = st + (r * un.bw + kx) * 32 * a.bpx; + if (nv < 32) { + zero_l1(seg + nv * a.bpx, (32 - nv) * a.bpx); + } + wr_page(a, spx(a, un.f, un.y0 + r, x0), seg); + } + } + wr_flush(); +} + +// RA page unit u (tokens [t0, t1) of token row y, page pg): every n-block of its token tiles -> the staging page +// (pixel t - t0, channels nb * chn ...) -> one whole page +MD_NOINL void run_ra(const Lay& L, uint32_t grp, uint32_t u) { + RaPage rp; + ra_page(pl, L.l, u, rp); + uint32_t m0, mt; + ra_unit(pl, L.l, u, m0, mt); + load_taps(L, grp, m0, mt, MD_TAPA_CAP); + const MapA a = map_of(L.dst); + const uint32_t chb = L.nbw * 64; + const uint32_t st = stage_base(); + const uint32_t tb0 = (m0 - rp.f * pl.hdr(H_PT)) * 32; // first token of tile m0 (frame-relative) + for (uint32_t nbi = 0; nbi < L.nbi; ++nbi) { + for (uint32_t mi = 0; mi < mt; ++mi) { + cbw_front(CB_OUT, OUT_BLK); + const uint32_t src = get_read_ptr(CB_OUT); + const uint32_t tb = tb0 + 32 * mi; + const uint32_t lo = rp.t0 > tb ? rp.t0 : tb; + const uint32_t hi = rp.t1 < tb + 32 ? rp.t1 : tb + 32; + if (chb == a.bpx) { + if (hi > lo) { + lcopy(src + (lo - tb) * chb, st + (lo - rp.t0) * a.bpx, (hi - lo) * chb); + } + } else { + for (uint32_t t = lo; t < hi; ++t) { + lcopy(src + (t - tb) * chb, st + (t - rp.t0) * a.bpx + nbi * chb, chb); + } + } + wr_flush(); + cb_pop_front(CB_OUT, OUT_BLK); + } + } + wr_bar(); + const uint32_t nv = rp.t1 - rp.t0; + if (nv < 32) { + zero_l1(st + nv * a.bpx, (32 - nv) * a.bpx); + } + wr_page(a, spx(a, rp.f, rp.y, 32 * rp.pg), st); + wr_flush(); +} + +// Units are software-pipelined: unit k + 1's inputs are read before unit k's outputs are written (the TRISC frees +// the band / residual / selector CBs before it produces outputs). Not for RA (the tap tiles are freed after the +// outputs) nor two-residual layers (the second residual of unit k + 1 lands only once the TRISC started it). +MD_NOINL void run_layer(uint32_t grp, uint32_t l) { + Lay L; + lay_of(l, L); + Sched s; + sched_of(pl, l, me_x, me_y, s); + const uint32_t U = pl.lf(l, L_U); +#ifdef MD_PIPE + const bool pipe = L.op != OP_RA && L.nres < 2; +#else + const bool pipe = false; // MD_PIPE (unit pipelining): opt-in, a device hang is not yet ruled out (MK_LOG) +#endif + bool have = false; + Unit pu; + uint32_t pg = 0; + for (uint32_t gi = 0; gi < s.ng; ++gi) { + const uint32_t g = s.g0 + gi * s.gstep; + for (uint32_t k = 0; k < s.rounds; ++k) { + const uint32_t u = k * s.span + s.off; + if (u >= U) { + continue; + } + if (L.op == OP_RA) { + run_ra(L, grp, u); + continue; + } + Unit un; + unit_of(pl, l, u, un); + load_inputs(L, un); + if (!pipe) { + drain(L, un, g, grp); + continue; + } + if (have) { + drain(L, pu, pg, grp); + } + pu = un; + pg = g; + have = true; + } + } + if (have) { + drain(L, pu, pg, grp); + } +} + +} // namespace + +void kernel_main() { + me_x = rt(A_X); + me_y = rt(A_Y); + g_spin = ca(K_SPIN); + g_dbg_word = W_DBG; + role = rt(A_ROLE); + ax0 = ca(K_ALL_X0); + ay0 = ca(K_ALL_Y0); + ax1 = ca(K_ALL_X1); + ay1 = ca(K_ALL_Y1); + nall = ca(K_N_ALL); + hubx = ca(K_HUB_X); + huby = ca(K_HUB_Y); + // zero the sync words, then the boot barrier (the NCRISC waits for SEM_GO before touching them) + for (uint32_t w = 0; w < N_SYNC; ++w) { + *sync_ptr(w) = 0; + } +#if MD_PROF + for (uint32_t w = 0; w < PROF_WORDS; ++w) { + reinterpret_cast(sync_addr(0) + SYNC_PROF)[w] = 0; + } +#endif + boot_barrier(); + // the plan table and the constants + cbr_back(CB_PLAN, 1); + { + const uint32_t bytes = ca(K_PLANB); + noc_async_read(dram(ca(K_PLANA), bytes).get_noc_addr(0), get_write_ptr(CB_PLAN), bytes); + rd_bar(); + } + cb_push_back(CB_PLAN, 1); + invalidate_l1_cache(); + pl.t = reinterpret_cast(cb_base(CB_PLAN)); + pl.nm = pl.t[H_NM]; + cbr_back(CB_CONST, N_CONST); + { + const auto acc = dram(ca(K_CONST), T16); + for (uint32_t i = 0; i < N_CONST; ++i) { + noc_async_read_page(i, acc, get_write_ptr(CB_CONST) + i * T16); + } + rd_bar(); + } + cb_push_back(CB_CONST, N_CONST); + uint32_t nl = ca(K_NL); + if (nl > pl.hdr(H_NL)) { + nl = pl.hdr(H_NL); + } + const uint32_t ngrp = g_abort ? 0 : pl.hdr(H_NGRP); +#if MD_PROF + volatile tt_l1_ptr uint32_t* pfw = reinterpret_cast(sync_addr(0) + SYNC_PROF); + const uint32_t pf0 = get_timestamp_32b(); +#endif + for (uint32_t grp = 0; grp < ngrp; ++grp) { + for (uint32_t l = 0; l < nl; ++l) { + *sync_ptr(W_DBG + 8) = grp * 1000 + l; + run_layer(grp, l); +#if MD_PROF + if (grp == 0 && l < 32) { + pfw[8 * l] = get_timestamp_32b() - pf0; + } +#endif + if (pl.lf(l, L_BAR) || l + 1 == nl) { + barrier(); + } +#if MD_PROF + if (grp == 0 && l < 32) { + pfw[8 * l + 1] = get_timestamp_32b() - pf0; + } +#endif + } + } + wr_bar(); +#if MD_PROF + noc_async_write(sync_addr(0) + SYNC_PROF, dram(ca(K_PROF), PROF_WORDS * 4).get_noc_addr(rt(A_IDX)), PROF_WORDS * 4); + wr_bar(); +#endif + // diagnostics of this core (abort codes of every RISC, last layer) -> K_DBG page idx + { + const uint32_t stg = sync_addr(0) + SYNC_STG; + volatile tt_l1_ptr uint32_t* o = reinterpret_cast(stg); + for (uint32_t i = 0; i < DBG_WORDS; ++i) { + o[i] = sync_read(W_DBG + i); + } + exit_barriers(1); + o[11] = sync_read(W_EXIT); // (the NCRISC's bit may land later; the BRISC's own is final here) + noc_async_write(stg, dram(ca(K_DBG), DBG_PAGE * 4).get_noc_addr(rt(A_IDX)), DBG_PAGE * 4); // 2 KB page + exit_barriers(1); + } +} diff --git a/code/tt_depthpro2/tt/mk_dec/kernels/md_defs.hpp b/code/tt_depthpro2/tt/mk_dec/kernels/md_defs.hpp new file mode 100644 index 0000000000000000000000000000000000000000..23b4c682d37b28975ced256975c2c83be5baff73 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_dec/kernels/md_defs.hpp @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// DepthPro2 DEC megakernel: fixed ids shared by the three RISC kernels AND the host (plan.py parses every +// `constexpr uint32_t NAME = ;` line of this file; one definition per line, integer literals only). +// Everything shape dependent (maps, layers, unit decomposition) is the plan table in the compile-time args. +#pragma once +#include + +namespace mdx { + +// ---------------------------------------------------------------- circular buffers +constexpr uint32_t CB_W = 0; // bf16 weight ring (NCRISC -> TRISC), pages of PAGE_TILES tiles +constexpr uint32_t CB_BAND = 1; // raw: the unit's ROW_MAJOR input band (one page = the whole band; BRISC -> TRISC) +constexpr uint32_t CB_TAPA = 2; // bf16 view of CB_BAND's memory: RA A tiles (BRISC -> TRISC), full-capacity cycles +constexpr uint32_t CB_A = 3; // bf16 tilized A tiles of one k-block (TRISC internal), full-capacity cycles +constexpr uint32_t CB_RES = 4; // raw: one ROW_MAJOR residual band (one page; BRISC -> TRISC) +constexpr uint32_t CB_ACC = 5; // fp32 accumulators of one unit (TRISC internal, UnpackToDestFp32), full cycles +constexpr uint32_t CB_OUT = 6; // bf16 ROW_MAJOR output blocks (32 rows x NBW tiles; TRISC -> BRISC), 2 x 8 pages +constexpr uint32_t CB_CONST = 7; // bf16 constants (C_*) +constexpr uint32_t CB_SEL = 8; // bf16 HC bias selector tiles of the unit (BRISC -> TRISC), full-capacity cycles +constexpr uint32_t CB_Z = 9; // bf16 HC: relu(head.2) of one M tile, the 4 sub-pixel tiles (TRISC internal) +constexpr uint32_t CB_HO = 10; // fp32 HC: one output tile, rows 0..3 = sub-pixels (TRISC -> BRISC), 2 pages +constexpr uint32_t CB_SYNC = 11; // raw: sync words + BRISC staging +constexpr uint32_t CB_PLAN = 12; // raw: the plan table (BRISC loads it from DRAM at boot; every RISC reads it) + +// ---------------------------------------------------------------- constants (CB_CONST tile index, bf16) +constexpr uint32_t C_E01 = 0; // ones in columns 0 and 1: in0 of a bias tile (rows 0 / 1 = bias hi / lo) +constexpr uint32_t C_I = 1; // identity +constexpr uint32_t C_W4H = 2; // 2 .. 5: head.4 weight hi in row s (s = sub-pixel 2a + b) +constexpr uint32_t C_W4L = 6; // 6 .. 9: head.4 weight lo in row s +constexpr uint32_t C_E4 = 10; // ones at (s, 0) and (s, 1) for s < 4: in0 of the head.4 bias +constexpr uint32_t C_B4T = 11; // column 0 = head.4 bias hi, column 1 = lo (all rows): in1 of the transposed matmul +constexpr uint32_t N_CONST = 12; + +// ---------------------------------------------------------------- ops +constexpr uint32_t OP_RA = 0; // 1x1 conv on the tapped tokens (TILE) -> ROW_MAJOR map +constexpr uint32_t OP_C3 = 1; // 3x3 conv (stride L_S 1 or 2, pad 1) [+ residuals], ROW_MAJOR -> ROW_MAJOR +constexpr uint32_t OP_UP = 2; // per-pixel matmul + depth-to-space (k = L_S): conv-transpose k x k stride k +constexpr uint32_t OP_HC = 3; // composite head: head.1 (convT k2s2) o head.2 (3x3) + relu + head.4 (1x1) + relu + +// layer flags +constexpr uint32_t F_RELU_IN = 1; +constexpr uint32_t F_RELU_OUT = 2; +constexpr uint32_t F_BIAS = 4; + +// ---------------------------------------------------------------- plan table (compile-time args from MD_PB) +// header +constexpr uint32_t H_NL = 0; // layers +constexpr uint32_t H_NM = 1; // maps +constexpr uint32_t H_G = 2; // frames per group +constexpr uint32_t H_NGRP = 3; // frame groups +constexpr uint32_t H_PT = 4; // patch tiles per frame (Np / 32) +constexpr uint32_t H_N = 5; // patches per frame +constexpr uint32_t H_GW = 6; // token grid width +constexpr uint32_t H_HP = 7; // padded frame height (output) +constexpr uint32_t H_WP = 8; // padded frame width (output) +constexpr uint32_t H_RING = 9; // weight ring pages +constexpr uint32_t H_KX_HC = 10; // HC: x tiles per row (Sel tiles per row class) +constexpr uint32_t NHF = 16; +// map fields +constexpr uint32_t M_H = 0; +constexpr uint32_t M_W = 1; +constexpr uint32_t M_WP = 2; // storage pixels per image row (ceil32(W + 1): rows start on DRAM pages) +constexpr uint32_t M_C = 3; // channels (multiple of 32) +constexpr uint32_t M_B0 = 4; // storage pixel of (0, 0) +constexpr uint32_t M_FPG = 5; // pages per frame (32 storage pixels per page) +constexpr uint32_t M_ARG = 6; // common runtime arg holding the map's DRAM address +constexpr uint32_t NMF = 8; +// layer fields +constexpr uint32_t L_OP = 0; +constexpr uint32_t L_SRC = 1; // map id (RA: tap index) +constexpr uint32_t L_DST = 2; // map id (HC: unused) +constexpr uint32_t L_RES0 = 3; // residual map ids +constexpr uint32_t L_RES1 = 4; +constexpr uint32_t L_NRES = 5; +constexpr uint32_t L_FLAGS = 6; +constexpr uint32_t L_S = 7; // C3: stride; UP: k +constexpr uint32_t L_CT = 8; // input channel tiles (RA: tap K tiles) +constexpr uint32_t L_KC = 9; // channel tiles per k-block +constexpr uint32_t L_NKB = 10; // k-blocks +constexpr uint32_t L_N = 11; // output tiles (N) +constexpr uint32_t L_NBW = 12; // tiles per n-block +constexpr uint32_t L_NBO = 13; // n-block groups split over grid-row groups +constexpr uint32_t L_NBI = 14; // n-blocks per group, iterated inside a unit +constexpr uint32_t L_BH = 15; // unit rows (RA: M tiles per unit) +constexpr uint32_t L_BW = 16; // unit x tiles +constexpr uint32_t L_YB = 17; // row blocks per frame +constexpr uint32_t L_XB = 18; // x blocks per row +constexpr uint32_t L_U = 19; // units +constexpr uint32_t L_WPG = 20; // first weight-arena page of the layer +constexpr uint32_t L_BP0 = 21; // pages of the k-block 0 block (incl. bias / selector-bias tiles) +constexpr uint32_t L_BP = 22; // pages of the other k-blocks +constexpr uint32_t L_HO = 23; // output rows (C3 / HC: map rows; UP: input rows) +constexpr uint32_t L_WO = 24; // output width +constexpr uint32_t L_KXO = 25; // M tiles per output row (ceil(WO / 32)) +constexpr uint32_t L_BANDP = 26; // band row pitch (bytes) +constexpr uint32_t L_NBIAS = 27; // bias tiles at the start of the k-block 0 block +constexpr uint32_t L_ACC = 28; // 1: fp32 L1 accumulators (CB_ACC); 0: pack straight from DST +constexpr uint32_t L_ROW0 = 29; // the layer runs on grid rows [ROW0, ROW0 + NROWS) (phase merging) +constexpr uint32_t L_NROWS = 30; +constexpr uint32_t L_BAR = 31; // 1: global barrier after the layer (end of its phase) +constexpr uint32_t L_PAIR = 32; // 1: kc == 1 k-blocks tilized in pairs (plan.pair_mode) +constexpr uint32_t L_BOFF = 33; // C3 / HC: byte offset of band row data (x = -1) after the left 2 KB edge chunk slack +constexpr uint32_t L_KPX = 34; // C3 / HC: pixels of one band edge chunk (>= 2 KB DRAM read) +constexpr uint32_t NLF = 40; + +// ---------------------------------------------------------------- sync words (CB_SYNC, SYNC_STRIDE bytes apart) +constexpr uint32_t SYNC_STRIDE = 16; +constexpr uint32_t W_BAR = 0; // every core: global barrier generation (hub multicast) +constexpr uint32_t W_BCNT = 1; // hub: barrier arrivals (cumulative) +constexpr uint32_t W_WVAL = 2; // ring receiver: weight pages valid (feeder multicast, cumulative) +constexpr uint32_t W_CRED = 4; // feeder: 4 + x = pages receiver column x has room for (cumulative), x < 16 +constexpr uint32_t W_SRC = 20; // 20 .. 23: local source words of the flag multicasts +constexpr uint32_t W_SRCV = 24; // 24 .. 31: the feeder's source words of the W_WVAL multicasts (ring of 8) +constexpr uint32_t N_SRCV = 8; +constexpr uint32_t W_DBG = 32; // 32 .. 47: abort diagnostics: +0 BRISC code, +1 its arg, +2 NCRISC code, +3 arg, + // +4/+5 TRISC unpack code/arg, +6/+7 pack code/arg, +8 BRISC layer, +9 unit +constexpr uint32_t N_SYNC = 48; +constexpr uint32_t SYNC_STG = 768; // byte offset of the BRISC staging area in CB_SYNC (2 KB debug page) +constexpr uint32_t SYNC_PROF = 2816; // byte offset of the PROF_WORDS profile words in CB_SYNC +constexpr uint32_t SYNC_BYTES = 3840; +constexpr uint32_t MIN_REQ = 2048; // every DRAM request of the map / output traffic is >= 2 KB (Blackhole SYS-1419) +constexpr uint32_t DBG_PAGE = 512; // uint32 words of one core's debug page (2 KB DRAM write) +// abort codes (a bounded wait gave up: the program finishes with garbage instead of hanging the device) +constexpr uint32_t AB_FRONT = 1; // wait for pages (arg: cb) +constexpr uint32_t AB_BACK = 2; // wait for room (arg: cb) +constexpr uint32_t AB_SYNC = 3; // sync word (arg: word) +constexpr uint32_t AB_PLAN = 4; // plan table +constexpr uint32_t AB_CRED = 5; // feeder credits +constexpr uint32_t AB_NOC = 6; // NoC barrier (arg: 1 reads, 2 write acks, 3 writes sent, 4 atomics) +constexpr uint32_t AB_PEER = 7; // another RISC of this core aborted (core abort word W_ABORT) +constexpr uint32_t W_ABORT = 44; // core abort word: any RISC that aborts sets it, every wait of every RISC polls it +constexpr uint32_t ABORT_MAGIC = 0xAB0A7E11u; // W_ABORT value (stale garbage from other programs never matches) +constexpr uint32_t W_EXIT = 45; // exit-hygiene outcome bits (BRISC 1 / NCRISC 2: final barriers timed out) + +// ---------------------------------------------------------------- roles (A_ROLE bits) +constexpr uint32_t R_FEED = 1; // weight feeder of its grid row (column 0) +constexpr uint32_t R_HUB = 2; // global barrier hub + +// ---------------------------------------------------------------- per-core runtime args +constexpr uint32_t A_IDX = 0; +constexpr uint32_t A_ROLE = 1; +constexpr uint32_t A_X = 2; +constexpr uint32_t A_Y = 3; +constexpr uint32_t A_ROWX0 = 4; // NoC x of logical columns 1 / C - 1 (feeder multicast rectangle) +constexpr uint32_t A_ROWX1 = 5; +constexpr uint32_t A_ROWY = 6; // NoC y of this core's row +constexpr uint32_t A_FX = 7; // NoC x / y of the row feeder +constexpr uint32_t A_FY = 8; +constexpr uint32_t N_RT_ARGS = 9; + +// ---------------------------------------------------------------- common runtime args +constexpr uint32_t K_ALL_X0 = 0; // whole-grid rectangle (NoC) +constexpr uint32_t K_ALL_Y0 = 1; +constexpr uint32_t K_ALL_X1 = 2; +constexpr uint32_t K_ALL_Y1 = 3; +constexpr uint32_t K_N_ALL = 4; +constexpr uint32_t K_HUB_X = 5; +constexpr uint32_t K_HUB_Y = 6; +constexpr uint32_t K_NL = 7; // layers run (all = the whole stage; fewer = debug) +constexpr uint32_t K_WTS = 8; // weight arena (ROW_MAJOR pages of PAGE_TILES bf16 tiles) +constexpr uint32_t K_CONST = 9; // bf16 constants [N_CONST * 32, 32] TILE +constexpr uint32_t K_SEL = 10; // bf16 HC selector tiles [3 * KX_HC * 32, 32] TILE +constexpr uint32_t K_OUT = 11; // inverse depth fp32 [T, Hp, Wp] TILE +constexpr uint32_t K_TAP0 = 12; // 12 .. 15: taps [T * Np, C] bf16 TILE +constexpr uint32_t K_PLANA = 16; // plan table (uint32 ROW_MAJOR, one page) +constexpr uint32_t K_PLANB = 17; // plan table bytes +constexpr uint32_t K_DBG = 18; // uint32 [NC, DBG_PAGE] ROW_MAJOR (first DBG_WORDS used): per-core abort diagnostics (W_DBG words) +constexpr uint32_t K_SPIN = 19; // spin-wait bound (iterations) before a wait aborts (hang protection) +constexpr uint32_t K_PROF = 20; // uint32 [NC, PROF_WORDS] ROW_MAJOR: per-layer time stamps (MD_PROF builds) +constexpr uint32_t K_MAP0 = 21; // 21 .. : map addresses +constexpr uint32_t N_COMMON_FIXED = 21; +constexpr uint32_t PROF_WORDS = 256; // 8 per layer: brisc work done, barrier exit, trisc w_wait, in_wait, tilize, + // mm, epilogue (accumulated ticks), spare +constexpr uint32_t DBG_WORDS = 16; + +// ---------------------------------------------------------------- compile-time args +constexpr uint32_t CT_ACC0 = 0; // TensorAccessorArgs (DRAM interleaved; page size given per use) +constexpr uint32_t PAGE_TILES = 8; +constexpr uint32_t T16 = 2048; +constexpr uint32_t T32 = 4096; +constexpr uint32_t OUT_CAP = 16; // CB_OUT pages (2 x the largest NBW) + +} // namespace mdx diff --git a/code/tt_depthpro2/tt/mk_dec/kernels/md_dm.hpp b/code/tt_depthpro2/tt/mk_dec/kernels/md_dm.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f71d763f95206b29f14465814beef7698f105182 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_dec/kernels/md_dm.hpp @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// DepthPro2 DEC megakernel: data-movement helpers shared by the BRISC and NCRISC kernels (mk_enc's me_dm.hpp). +#pragma once + +#include +#include "api/dataflow/dataflow_api.h" +#include "api/debug/waypoint.h" +#include "md_plan.hpp" + +namespace mdx { + +FORCE_INLINE uint32_t rt(uint32_t i) { return get_arg_val(i); } +FORCE_INLINE uint32_t ca(uint32_t i) { return get_common_arg_val(i); } + +// Byte address of a CB's buffer base (LocalCBInterface keeps it in 16 B units): identical on every core. +FORCE_INLINE uint32_t cb_base(uint32_t cb) { + const auto& iface = get_local_cb_interface(cb); + return (iface.fifo_limit - iface.fifo_size) << cb_addr_shift; +} + +FORCE_INLINE uint32_t sync_addr(uint32_t w) { return cb_base(CB_SYNC) + w * SYNC_STRIDE; } +FORCE_INLINE volatile tt_l1_ptr uint32_t* sync_ptr(uint32_t w) { + return reinterpret_cast(sync_addr(w)); +} +FORCE_INLINE uint32_t sync_read(uint32_t w) { + invalidate_l1_cache(); + asm volatile("" ::: "memory"); + return *sync_ptr(w); +} + +// Multicast NoC address of the rectangle (x0, y0)-(x1, y1) given in NoC-0 virtual coordinates (start = min corner); +// NoC 1 addresses the rectangle end-first. +FORCE_INLINE uint64_t mcast_addr(uint32_t x0, uint32_t y0, uint32_t x1, uint32_t y1, uint32_t addr) { + if (noc_index == 0) { + return NOC_MULTICAST_ADDR( + DYNAMIC_NOC_X(0, x0), DYNAMIC_NOC_Y(0, y0), DYNAMIC_NOC_X(0, x1), DYNAMIC_NOC_Y(0, y1), addr); + } + return NOC_MULTICAST_ADDR( + DYNAMIC_NOC_X(1, x1), DYNAMIC_NOC_Y(1, y1), DYNAMIC_NOC_X(1, x0), DYNAMIC_NOC_Y(1, y0), addr); +} + +// Tiles of the weight ring the TRISC has not yet released (16-bit received / acked counters). +FORCE_INLINE uint32_t ring_outstanding_tiles() { + invalidate_l1_cache(); + asm volatile("" ::: "memory"); + const uint16_t received = (uint16_t)get_cb_tiles_received_ptr(CB_W)[0]; + const uint16_t acked = (uint16_t)reg_read((uintptr_t)get_cb_tiles_acked_ptr(CB_W)); + return (uint16_t)(received - acked); +} + +// ------------------------------------------------------------------ bounded waits (hang protection) +inline uint32_t g_abort = 0; +inline uint32_t g_spin = 1u << 26; +inline uint32_t g_dbg_word = W_DBG; // BRISC: W_DBG, NCRISC: W_DBG + 2 +FORCE_INLINE void abort_note(uint32_t code, uint32_t arg) { + if (!g_abort) { + g_abort = code; + *sync_ptr(g_dbg_word) = code; + *sync_ptr(g_dbg_word + 1) = arg; + *sync_ptr(W_ABORT) = ABORT_MAGIC; // releases every other RISC of this core (their waits poll it) + } +} +// polled every 4096 spins inside every wait: another RISC of this core aborted -> stop waiting too +FORCE_INLINE bool peer_abort(uint32_t it) { + if ((it & 4095) == 0 && sync_read(W_ABORT) == ABORT_MAGIC) { + abort_note(AB_PEER, 0); + return true; + } + return false; +} +__attribute__((noinline)) inline void cbw_front(int32_t cb, int32_t n) { + if (g_abort) { + return; + } + const uint32_t acked = get_cb_tiles_acked_ptr(cb)[0]; + const uintptr_t rp = (uintptr_t)get_cb_tiles_received_ptr(cb); + uint32_t it = 0; + WAYPOINT("CWFW"); + while ((uint16_t)(((uint16_t)reg_read(rp)) - acked) < (uint16_t)n) { + if (++it > g_spin) { + abort_note(AB_FRONT, cb); + return; + } + if (peer_abort(it)) { + return; + } + } +} +__attribute__((noinline)) inline void cbr_back(int32_t cb, int32_t n) { + if (g_abort) { + return; + } + const uintptr_t ap = (uintptr_t)get_cb_tiles_acked_ptr(cb); + const uint32_t received = get_cb_tiles_received_ptr(cb)[0]; + uint32_t it = 0; + WAYPOINT("CRBW"); + while (true) { + invalidate_l1_cache(); + const uint16_t acked = (uint16_t)reg_read(ap); + const uint16_t fr = get_local_cb_interface(cb).fifo_num_pages - (uint16_t)(received - acked); + if ((int32_t)fr >= n) { + break; + } + if (++it > g_spin) { + abort_note(AB_BACK, cb); + return; + } + if (peer_abort(it)) { + return; + } + } +} +// spin until sync word w >= v (bounded) +__attribute__((noinline)) inline void spin_ge(uint32_t w, uint32_t v) { + if (g_abort) { + return; + } + uint32_t it = 0; + while (sync_read(w) < v) { + if (++it > g_spin) { + abort_note(AB_SYNC, w); + return; + } + if (peer_abort(it)) { + return; + } + } +} + +// bounded NoC barriers (dedicated NoC mode): a transaction that never completes aborts instead of hanging +__attribute__((noinline)) inline void rd_bar() { + uint32_t it = 0; + while (!g_abort && !ncrisc_noc_reads_flushed(noc_index)) { + if (++it > g_spin) { + abort_note(AB_NOC, 1); + } + peer_abort(it); + } + invalidate_l1_cache(); +} +__attribute__((noinline)) inline void wr_bar() { + uint32_t it = 0; + while (!g_abort && !ncrisc_noc_nonposted_writes_flushed(noc_index)) { + if (++it > g_spin) { + abort_note(AB_NOC, 2); + } + peer_abort(it); + } + invalidate_l1_cache(); +} +__attribute__((noinline)) inline void wr_flush() { + uint32_t it = 0; + while (!g_abort && !ncrisc_noc_nonposted_writes_sent(noc_index)) { + if (++it > g_spin) { + abort_note(AB_NOC, 3); + } + peer_abort(it); + } + invalidate_l1_cache(); +} +__attribute__((noinline)) inline void at_bar() { + uint32_t it = 0; + while (!g_abort && !ncrisc_noc_nonposted_atomics_flushed(noc_index)) { + if (++it > g_spin) { + abort_note(AB_NOC, 4); + } + peer_abort(it); + } + invalidate_l1_cache(); +} + +// exit hygiene: every read landed, every non-posted write and atomic acked, even after an abort (bounded; a stale +// transaction must not land in the next launch). bit: W_EXIT bit of this RISC if a barrier timed out +__attribute__((noinline)) inline void exit_barriers(uint32_t bit) { + uint32_t it = 0; + const uint32_t lim = g_spin << 2; + while (!(ncrisc_noc_reads_flushed(noc_index) && ncrisc_noc_nonposted_writes_flushed(noc_index) && + ncrisc_noc_nonposted_atomics_flushed(noc_index))) { + if (++it > lim) { + *sync_ptr(W_EXIT) = *sync_ptr(W_EXIT) | bit; + break; + } + } + invalidate_l1_cache(); +} + +// the plan table landed in CB_PLAN (the BRISC pushes it once at boot) +FORCE_INLINE Plan wait_plan() { + WAYPOINT("PLNW"); + uint32_t it = 0; + while (true) { + invalidate_l1_cache(); + if ((uint16_t)get_cb_tiles_received_ptr(CB_PLAN)[0] != 0) { + break; + } + if (++it > g_spin) { + abort_note(AB_PLAN, 0); + break; + } + } + invalidate_l1_cache(); + Plan p; + p.t = reinterpret_cast(cb_base(CB_PLAN)); + p.nm = p.t[H_NM]; + return p; +} + +// boot barrier: every core zeroed its sync words before anyone exchanges (semaphores reset at program launch) +FORCE_INLINE void wait_go(uint32_t sem_go_addr) { + volatile tt_l1_ptr uint32_t* go = reinterpret_cast(sem_go_addr); + WAYPOINT("BGO "); + uint32_t it = 0; + while (true) { + invalidate_l1_cache(); + if (*go >= 1) { + break; + } + if (++it > g_spin) { + abort_note(AB_SYNC, 999); + break; + } + } +} + +} // namespace mdx diff --git a/code/tt_depthpro2/tt/mk_dec/kernels/md_ncrisc.cpp b/code/tt_depthpro2/tt/mk_dec/kernels/md_ncrisc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8cec5915927d1e12ab00952d66f3e78129d9e3c3 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_dec/kernels/md_ncrisc.cpp @@ -0,0 +1,237 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// DepthPro2 DEC megakernel, NCRISC (NoC 0): the weight ring of each grid row (mk_enc's ring protocol, row multicast). +// feeder (0, y): walks the row's schedule and, page by page, reads the weight-arena page from DRAM straight into +// its own ring slot, pushes it for its own TRISC and multicasts it to the same slot of columns +// 1 .. GX - 1 of its row, then the cumulative valid count (W_WVAL). A page goes out only when every +// receiver granted it (per-receiver credits W_CRED + x). Blocks never wrap the ring: the pages a +// block would wrap over are sent as skip pages (any arena page; the TRISC pops them unused). +// receiver : grants ring slots as its TRISC frees them and pushes the pages the feeder flagged valid. +#include "md_dm.hpp" + +using namespace mdx; + +namespace { + +constexpr auto acc_dram = TensorAccessorArgs(); +#ifndef MD_FEED_DEPTH +#define MD_FEED_DEPTH 4 +#endif +constexpr uint32_t DEPTH = MD_FEED_DEPTH; // outstanding weight-page DRAM reads (transaction ids 1 .. DEPTH) +constexpr uint32_t PAGE_BYTES = PAGE_TILES * T16; +constexpr uint32_t NRECV = GX - 1; + +Plan pl; +uint32_t SLOTS = 0; + +FORCE_INLINE uint32_t freed_pages(uint32_t pushed) { + const uint32_t out = ring_outstanding_tiles(); + return pushed - (out + PAGE_TILES - 1) / PAGE_TILES; +} + +// ------------------------------------------------------------------ the row's page sequence +// calls emit(arena page) for every ring page of the row, in order +template +FORCE_INLINE void walk(uint32_t x, uint32_t y, uint32_t nl, F&& emit) { + uint32_t pos = 0; + const uint32_t ngrp = pl.hdr(H_NGRP); + for (uint32_t grp = 0; grp < ngrp; ++grp) { + for (uint32_t l = 0; l < nl; ++l) { + Sched s; + sched_of(pl, l, x, y, s); + const uint32_t nbi_n = pl.lf(l, L_NBI), nkb = pl.lf(l, L_NKB); + for (uint32_t gi = 0; gi < s.ng; ++gi) { + const uint32_t g = s.g0 + gi * s.gstep; + for (uint32_t k = 0; k < s.rounds; ++k) { + for (uint32_t nbi = 0; nbi < nbi_n; ++nbi) { + const uint32_t nb = g * nbi_n + nbi; + for (uint32_t kb = 0; kb < nkb; ++kb) { + const uint32_t np = blk_pages(pl, l, kb); + const uint32_t skip = ring_skip(pos, np, SLOTS); + for (uint32_t i = 0; i < skip; ++i) { + emit(0u); + } + const uint32_t p0 = blk_page(pl, l, nb, kb); + for (uint32_t i = 0; i < np; ++i) { + emit(p0 + i); + } + pos += skip + np; + } + } + } + } + } + } +} + +// ------------------------------------------------------------------ receiver +void receiver(uint32_t total, uint32_t x) { + const uint64_t cred = get_noc_addr(rt(A_FX), rt(A_FY), sync_addr(W_CRED + x)); + uint32_t granted = 0, pushed = 0, idle = 0; + while (pushed < total && !g_abort) { + WAYPOINT("NRCV"); + if (++idle > g_spin) { + abort_note(AB_SYNC, W_WVAL); + break; + } + if (peer_abort(idle)) { + break; + } + if (granted < total) { + uint32_t lim = freed_pages(pushed) + SLOTS; + if (lim > total) { + lim = total; + } + if (lim > granted) { + noc_semaphore_inc(cred, lim - granted); + granted = lim; + } + } + const uint32_t v = sync_read(W_WVAL); + if (v > pushed) { + cb_push_back(CB_W, (v - pushed) * PAGE_TILES); + pushed = v; + idle = 0; + } + } + at_bar(); +} + +// ------------------------------------------------------------------ feeder +struct Feeder { + uint32_t rd_issued = 0, rd_done = 0, mc_done = 0, mc_flushed = 0; + uint32_t base = 0, wval = 0, x0 = 0, x1 = 0, ry = 0, wts = 0; + + FORCE_INLINE void service() { + if (rd_done < rd_issued && ncrisc_noc_read_with_transaction_id_flushed(noc_index, 1 + (rd_done % DEPTH))) { + invalidate_l1_cache(); + ++rd_done; + cb_push_back(CB_W, PAGE_TILES); + } + if (NRECV > 0 && mc_done < rd_done) { + uint32_t mn = 0xFFFFFFFFu; + for (uint32_t r = 1; r <= NRECV; ++r) { + const uint32_t c = sync_read(W_CRED + r); + mn = c < mn ? c : mn; + } + if (mn > mc_done) { + if (mc_done - mc_flushed >= N_SRCV) { + wr_flush(); + mc_flushed = mc_done; + } + const uint32_t a = base + (mc_done % SLOTS) * PAGE_BYTES; + const uint32_t src = sync_addr(W_SRCV + (mc_done % N_SRCV)); +#if defined(MD_MCAST_SAFE) && MD_MCAST_SAFE == 1 + // unlinked data multicast, acked before the flag multicast (no held link; strict ordering) + noc_async_write_multicast(a, mcast_addr(x0, ry, x1, ry, a), PAGE_BYTES, NRECV, false); + wr_bar(); + *reinterpret_cast(src) = mc_done + 1; + noc_semaphore_set_multicast(src, mcast_addr(x0, ry, x1, ry, wval), NRECV); + wr_bar(); +#elif defined(MD_MCAST_SAFE) && MD_MCAST_SAFE == 2 + // unlinked data multicast, flag ordered behind it by the static multicast VC (no barrier) + noc_async_write_multicast(a, mcast_addr(x0, ry, x1, ry, a), PAGE_BYTES, NRECV, false); + *reinterpret_cast(src) = mc_done + 1; + noc_semaphore_set_multicast(src, mcast_addr(x0, ry, x1, ry, wval), NRECV); +#else + noc_async_write_multicast(a, mcast_addr(x0, ry, x1, ry, a), PAGE_BYTES, NRECV, true); + *reinterpret_cast(src) = mc_done + 1; + noc_semaphore_set_multicast(src, mcast_addr(x0, ry, x1, ry, wval), NRECV); +#endif + ++mc_done; +#ifdef MD_FEED_SERIAL + wr_flush(); // one page multicast in flight at a time (NoC-load experiment) + mc_flushed = mc_done; +#endif + } + } else if (NRECV == 0) { + mc_done = rd_done; + } + } + + FORCE_INLINE void emit(uint32_t page) { + uint32_t idle = 0; + while (!g_abort) { + WAYPOINT("NFED"); + if (++idle > g_spin) { + abort_note(AB_CRED, rd_issued); + return; + } + if (peer_abort(idle)) { + return; + } + if (rd_issued - rd_done < DEPTH && rd_issued < freed_pages(rd_done) + SLOTS) { + bool ok = true; + if (rd_issued >= SLOTS) { + const uint32_t prev = rd_issued - SLOTS; + if (mc_done <= prev) { + ok = false; + } else if (mc_flushed <= prev) { + wr_flush(); + mc_flushed = mc_done; + } + } + if (ok) { + noc_async_read_set_trid(1 + (rd_issued % DEPTH)); + const auto acc = TensorAccessor(acc_dram, wts, PAGE_BYTES); + noc_async_read_page(page, acc, base + (rd_issued % SLOTS) * PAGE_BYTES); + ++rd_issued; + return; + } + } + service(); + } + } + + FORCE_INLINE void finish() { + uint32_t idle = 0; + while ((rd_done < rd_issued || mc_done < rd_done) && !g_abort) { + service(); + if (++idle > g_spin) { + abort_note(AB_CRED, 1000000 + mc_done); + break; + } + if (peer_abort(idle)) { + break; + } + } + noc_async_read_set_trid(0); + wr_bar(); + } +}; + +} // namespace + +void kernel_main() { + const uint32_t role = rt(A_ROLE); + const uint32_t x = rt(A_X), y = rt(A_Y); + g_spin = ca(K_SPIN); + g_dbg_word = W_DBG + 2; + wait_go(get_semaphore(1)); // SEM_GO: the BRISCs zeroed every sync word + pl = wait_plan(); + if (g_abort) { + return; + } + SLOTS = pl.hdr(H_RING); + uint32_t nl = ca(K_NL); + if (nl > pl.hdr(H_NL)) { + nl = pl.hdr(H_NL); + } + if (role & R_FEED) { + Feeder f; + f.base = cb_base(CB_W); + f.wval = sync_addr(W_WVAL); + f.x0 = rt(A_ROWX0); + f.x1 = rt(A_ROWX1); + f.ry = rt(A_ROWY); + f.wts = ca(K_WTS); + walk(x, y, nl, [&](uint32_t page) { f.emit(page); }); + f.finish(); + } else { + uint32_t total = 0; + walk(x, y, nl, [&](uint32_t) { ++total; }); + receiver(total, x); + } + noc_async_read_set_trid(0); + exit_barriers(2); +} diff --git a/code/tt_depthpro2/tt/mk_dec/kernels/md_plan.hpp b/code/tt_depthpro2/tt/mk_dec/kernels/md_plan.hpp new file mode 100644 index 0000000000000000000000000000000000000000..86a674ccba08790cdafbacf5e4ddf55488d4d214 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_dec/kernels/md_plan.hpp @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// DepthPro2 DEC megakernel: plan-table access and the work schedule. The BRISC, NCRISC and TRISC walk the same +// schedule (frame groups x layers x my n-block groups x rounds x n-blocks x k-blocks), so their CB / ring traffic +// matches by construction. The plan table (host: plan.py Plan.table()) is loaded into CB_PLAN by the BRISC at boot. +#pragma once +#include +#include "md_defs.hpp" + +#define MD_INL inline __attribute__((always_inline)) + +namespace mdx { + +constexpr uint32_t GX = MD_GX; // grid columns +constexpr uint32_t GY = MD_GY; // grid rows + +struct Plan { + const uint32_t* t; + uint32_t nm; + MD_INL uint32_t hdr(uint32_t f) const { return t[f]; } + MD_INL uint32_t mf(uint32_t m, uint32_t f) const { return t[NHF + m * NMF + f]; } + MD_INL uint32_t lf(uint32_t l, uint32_t f) const { return t[NHF + nm * NMF + l * NLF + f]; } +}; + +MD_INL uint32_t cdiv(uint32_t a, uint32_t b) { return (a + b - 1) / b; } + +// my share of a layer's work: n-block groups g = g0 + i * gstep (i < ng); in round k my unit is k * span + off. +// The layer runs on grid rows [row0, row0 + nrows) (phase merging); other rows have no work (ng = 0). +struct Sched { + uint32_t g0, gstep, ng, span, off, rounds; +}; +MD_INL void sched_rows(uint32_t nbo, uint32_t u, uint32_t x, uint32_t y, uint32_t NR, Sched& s) { + if (nbo <= NR) { + const uint32_t q = NR / nbo; + s.gstep = 1; + if (y < nbo * q) { + s.g0 = y / q; + s.ng = 1; + s.off = (y % q) * GX + x; + s.span = q * GX; + } else { + s.g0 = 0; + s.ng = 0; + s.off = 0; + s.span = GX; + } + } else { + s.g0 = y; + s.gstep = NR; + s.ng = y < nbo ? (nbo - y + NR - 1) / NR : 0; + s.off = x; + s.span = GX; + } + s.rounds = cdiv(u, s.span); +} + +MD_INL void sched_of(const Plan& p, uint32_t l, uint32_t x, uint32_t y, Sched& s) { + const uint32_t r0 = p.lf(l, L_ROW0), nr = p.lf(l, L_NROWS); + if (y < r0 || y >= r0 + nr) { + s.g0 = s.ng = s.off = 0; + s.gstep = 1; + s.span = GX; + s.rounds = 0; + return; + } + sched_rows(p.lf(l, L_NBO), p.lf(l, L_U), x, y - r0, nr, s); +} + +// weight blocks: (nb, kb) of layer l -> first arena page, pages +MD_INL uint32_t blk_page(const Plan& p, uint32_t l, uint32_t nb, uint32_t kb) { + const uint32_t bp0 = p.lf(l, L_BP0), bp = p.lf(l, L_BP); + return p.lf(l, L_WPG) + nb * (bp0 + (p.lf(l, L_NKB) - 1) * bp) + (kb == 0 ? 0 : bp0 + (kb - 1) * bp); +} +MD_INL uint32_t blk_pages(const Plan& p, uint32_t l, uint32_t kb) { return kb == 0 ? p.lf(l, L_BP0) : p.lf(l, L_BP); } +// pages to skip so that a block of np pages starting at ring position pos does not wrap +MD_INL uint32_t ring_skip(uint32_t pos, uint32_t np, uint32_t ring) { + const uint32_t r = pos % ring; + return r + np > ring ? ring - r : 0; +} + +// unit geometry (C3 / UP / HC): u -> frame f, first output row y0, first x tile kx0, rows bh, x tiles bw +struct Unit { + uint32_t f, y0, kx0, bh, bw; +}; +MD_INL void unit_of(const Plan& p, uint32_t l, uint32_t u, Unit& un) { + const uint32_t yb = p.lf(l, L_YB), xb = p.lf(l, L_XB); + const uint32_t BH = p.lf(l, L_BH), BW = p.lf(l, L_BW); + un.f = u / (yb * xb); + const uint32_t rem = u - un.f * yb * xb; + const uint32_t by = rem / xb, bx = rem - by * xb; + un.y0 = by * BH; + un.kx0 = bx * BW; + const uint32_t ho = p.lf(l, L_HO), kxo = p.lf(l, L_KXO); + un.bh = ho - un.y0 < BH ? ho - un.y0 : BH; + un.bw = kxo - un.kx0 < BW ? kxo - un.kx0 : BW; +} +// RA unit u = output map page: frame f (of the group), token row y, page pg -> tokens [t0, t1) of the frame +// (t = y gw + x, x in [32 pg, min(32 pg + 32, gw))); its token tiles [m0, m0 + mt) of the group's flat list (G * PT) +struct RaPage { + uint32_t f, y, pg, t0, t1; +}; +MD_INL void ra_page(const Plan& p, uint32_t l, uint32_t u, RaPage& r) { + const uint32_t gh = p.lf(l, L_HO), gw = p.lf(l, L_WO); + const uint32_t npg = (gw + 31) / 32; + r.f = u / (gh * npg); + const uint32_t rem = u - r.f * gh * npg; + r.y = rem / npg; + r.pg = rem - r.y * npg; + r.t0 = r.y * gw + 32 * r.pg; + r.t1 = r.y * gw + (32 * r.pg + 32 < gw ? 32 * r.pg + 32 : gw); +} +MD_INL void ra_unit(const Plan& p, uint32_t l, uint32_t u, uint32_t& m0, uint32_t& mt) { + RaPage r; + ra_page(p, l, u, r); + const uint32_t pt = p.lf(l, L_KXO); + m0 = r.f * pt + r.t0 / 32; + mt = (r.t1 - 1) / 32 - r.t0 / 32 + 1; +} + +} // namespace mdx diff --git a/code/tt_depthpro2/tt/mk_dec/kernels/md_trisc.cpp b/code/tt_depthpro2/tt/mk_dec/kernels/md_trisc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9bdfe446e7a28b62985a9eedbdb8f49e6a61a7cc --- /dev/null +++ b/code/tt_depthpro2/tt/mk_dec/kernels/md_trisc.cpp @@ -0,0 +1,651 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// DepthPro2 DEC megakernel, TRISC: all arithmetic. +// tilize : ROW_MAJOR runs of the unit's L1 band -> bf16 A tiles (straight from the band at any 16 B aligned +// address: the tilize unpacker gets the run's address, its row pitch is the band's pixel pitch x stride; +// input ReLU = packer ReLU of this pack); residual maps -> the fp32 accumulators (L1 accumulation) +// matmul : per output tile, the k-block's taps x channel tiles (+ the bias tile through the ones operand E01 in +// k-block 0; HC: the per-pixel-class bias through the selector tile), fp32 DST (half sync, 4 tiles), +// packed into the fp32 accumulators (L1 accumulation from the second contribution on), or (UP / RA with +// one k-block) pack-untilized straight into the ROW_MAJOR output block +// epilog : C3: accumulators -> (packer ReLU) -> pack-untilize -> CB_OUT; HC: relu(acc) -> bf16 Z (4 sub-pixel +// tiles) -> R = sum_s w4_s Z_s^T + b4 (transposed matmuls, rows = sub-pixels) -> ReLU -> fp32 CB_HO +// Every CB with layer-dependent use is cycled at full capacity (pointers stay at the base); the weight ring is +// consumed in blocks that never wrap (skip pages, md_plan.hpp ring_skip, mirrored by the NCRISC). +#include +#include "api/compute/compute_kernel_api.h" +#include "api/compute/matmul.h" +#include "api/compute/tilize.h" +#include "api/compute/pack_untilize.h" +#include "api/compute/tile_move_copy.h" +#include "api/compute/pack.h" +#include "api/compute/reconfig_data_format.h" +#include "api/compute/compute_kernel_hw_startup.h" +#include "stream_io_map.h" +#include "dev_mem_map.h" +#include "hostdev/dev_msgs.h" +#include "md_plan.hpp" + +#define NOINL __attribute__((noinline, noclone)) + +using namespace mdx; + +namespace { + +#ifdef MD_FID +constexpr MathFidelity FID = static_cast(MD_FID); +#else +constexpr MathFidelity FID = MathFidelity::HiFi4; +#endif +constexpr uint32_t A_CAP = MD_A_CAP; +constexpr uint32_t ACC_CAP = MD_ACC_CAP; +constexpr uint32_t TAPA_CAP = MD_TAPA_CAP; +constexpr uint32_t SEL_CAP = MD_SEL_CAP; +constexpr uint32_t OUT_BLK = 8; +constexpr uint32_t Z_CAP = 16; + +Plan pl; +uint32_t ring_pos = 0, RING = 0; +uint32_t g_abort = 0, g_spin = 1u << 26; + +// L1 byte address of a CB's buffer from this program's CB config (the MATH thread has no CB interfaces) +NOINL uint32_t cb_addr(uint32_t cb) { + tt_l1_ptr mailboxes_t* const mb = (tt_l1_ptr mailboxes_t*)(MEM_MAILBOX_BASE); + const tt_l1_ptr launch_msg_t* lm = &(mb->launch[mb->launch_msg_rd_ptr]); + const uint32_t base = lm->kernel_config.kernel_config_base[ProgrammableCoreType::TENSIX]; + const volatile tt_l1_ptr uint32_t* cfg = + reinterpret_cast(base + lm->kernel_config.local_cb_offset); + return cfg[cb * 4]; // [fifo_addr, fifo_size, num_pages, page_size] in bytes +} + +// ---------------------------------------------------------------- bounded waits (hang protection, md_dm.hpp) +uint32_t g_sync = 0; +ALWI volatile uint32_t* dbg_ptr(uint32_t w) { return reinterpret_cast(g_sync + w * SYNC_STRIDE); } +NOINL void note(uint32_t word, uint32_t code, uint32_t arg) { + if (!g_abort) { + g_abort = code; + *dbg_ptr(word) = code; + *dbg_ptr(word + 1) = arg; + *dbg_ptr(W_ABORT) = ABORT_MAGIC; // releases the data-movement RISCs of this core + } +} +// another RISC of this core aborted (polled every 4096 spins) +ALWI bool peer_abort(uint32_t it, uint32_t word) { + if ((it & 4095) == 0 && *dbg_ptr(W_ABORT) == ABORT_MAGIC) { + note(word, AB_PEER, 0); + return true; + } + return false; +} +// cb_wait_front (UNPACK) +NOINL void cbw(uint32_t cb, uint32_t n) { + UNPACK(({ + if (!g_abort) { + volatile uint32_t* rp = get_cb_tiles_received_ptr(cb); + uint32_t it = 0; + while (true) { + const uint16_t have = (uint16_t)reg_read((uint32_t)rp) - (uint16_t)get_local_cb_interface(cb).tiles_acked; + if (have >= (uint16_t)n) { + break; + } + if (++it > g_spin) { + note(W_DBG + 4, AB_FRONT, cb); + break; + } + if (peer_abort(it, W_DBG + 4)) { + break; + } + } + } + })); +} +// cb_reserve_back (PACK) +NOINL void cbr(uint32_t cb, uint32_t n) { + PACK(({ + if (!g_abort) { + volatile uint32_t* ap = get_cb_tiles_acked_ptr(cb); + const uint16_t rcv = (uint16_t)get_local_cb_interface(cb).tiles_received; + uint32_t it = 0; + while (true) { + const uint16_t acked = (uint16_t)reg_read((uint32_t)ap); + const uint16_t fr = (uint16_t)get_local_cb_interface(cb).fifo_num_pages - (uint16_t)(rcv - acked); + if ((int32_t)fr >= (int32_t)n) { + break; + } + if (++it > g_spin) { + note(W_DBG + 6, AB_BACK, cb); + break; + } + if (peer_abort(it, W_DBG + 6)) { + break; + } + } + } + })); +} + +// ---------------------------------------------------------------- profiling (MD_PROF builds, UNPACK thread) +#if MD_PROF +uint32_t pf_l = 0; +uint64_t pf_t = 0; +NOINL void pf_start(uint32_t l) { + UNPACK(({ + pf_l = l; + pf_t = ckernel::read_wall_clock(); + })); +} +// attribute the time since the last mark to slot (2 w_wait, 3 in_wait, 4 tilize, 5 mm, 6 epilogue) +NOINL void pf_mark(uint32_t slot) { + UNPACK(({ + const uint64_t now = ckernel::read_wall_clock(); + if (pf_l < 32) { + volatile uint32_t* p = reinterpret_cast(g_sync + SYNC_PROF); + p[8 * pf_l + slot] += (uint32_t)(now - pf_t); + } + pf_t = now; + })); +} +#else +ALWI void pf_start(uint32_t) {} +ALWI void pf_mark(uint32_t) {} +#endif + +// ---------------------------------------------------------------- plan (all three threads) +NOINL void wait_plan_all() { + volatile uint32_t* p = get_cb_tiles_received_ptr(CB_PLAN); + uint32_t it = 0; + while ((p[0] & 0xFFFFu) == 0) { + if (++it > g_spin) { + break; + } + } + asm volatile("" ::: "memory"); + pl.t = reinterpret_cast(cb_addr(CB_PLAN)); + pl.nm = pl.t[H_NM]; +} + +// ---------------------------------------------------------------- LLK wrappers +ALWI void mm_init_f(uint32_t in0, uint32_t in1, uint32_t transpose = 0) { + reconfig_data_format(in1, in0); // matmul: SrcA <- in1, SrcB <- in0 + MATH((llk_math_matmul_init(in0, in1, transpose))); + UNPACK((llk_unpack_AB_matmul_init(in0, in1, transpose))); +} +ALWI void mm_f(uint32_t in0, uint32_t in1, uint32_t t0, uint32_t t1, uint32_t dst) { + UNPACK((llk_unpack_AB_matmul(in0, in1, t0, t1))); + MATH((llk_math_matmul(dst))); +} +NOINL void mm_init_n(uint32_t in0, uint32_t in1, uint32_t transpose) { mm_init_f(in0, in1, transpose); } +NOINL void pk(uint32_t ocb, uint32_t l1acc) { + pack_reconfig_data_format(ocb); + PACK((llk_pack_reconfig_l1_acc(l1acc))); +} +NOINL void relu_on() { PACK((llk_pack_relu_config(ReluConfig::zero()))); } +NOINL void relu_off() { PACK((llk_pack_relu_config(ReluConfig::none()))); } + +// tilize (BH: the regular tilize unpack only handles 1-tile-wide rows, so rows wider than one tile go through the +// fast-tilize path, like DA3): the run's L1 address is set as the input CB's read pointer, the row pitch (in 32-datum +// column tiles) is given at init; 2-4 tile chunks. One tile out of a wider row is tilized as a 2-tile chunk whose +// second tile lands in the next output slot (rewritten by the next run, or the spare slot at the end). +uint32_t ft_saved = 0; +NOINL void ft_begin(uint32_t icb, uint32_t pitch, uint32_t ocb, bool relu) { + UNPACK((ft_saved = get_local_cb_interface(icb).fifo_rd_ptr)); + reconfig_data_format_srca(icb); + pk(ocb, 0); + if (relu) { + relu_on(); + } + fast_tilize_init(icb, pitch, ocb); +} +NOINL void ft_end(uint32_t icb, uint32_t ocb, uint32_t pitch, bool relu) { + fast_tilize_uninit(icb, ocb, pitch); + if (relu) { + relu_off(); + } + UNPACK((get_local_cb_interface(icb).fifo_rd_ptr = ft_saved)); +} +// nt channel tiles of the 32-row run starting at L1 address (src16 << 4) -> ocb[oidx ..] +NOINL void ft_run(uint32_t icb, uint32_t src16, uint32_t nt, uint32_t pitch, uint32_t ocb, uint32_t oidx) { + UNPACK((get_local_cb_interface(icb).fifo_rd_ptr = src16)); + fast_tilize_block(icb, (pitch > 1 && nt < 2) ? 2 : nt, ocb, 0, oidx); +} +// L1 byte address >> 4 of a CB's read pointer (UNPACK thread; 0 elsewhere) +ALWI uint32_t rd16(uint32_t cb) { + uint32_t a = 0; + UNPACK((a = get_local_cb_interface(cb).fifo_rd_ptr)); + return a; +} + +// ---------------------------------------------------------------- weight ring +NOINL void w_wait(uint32_t np) { + pf_mark(5); + const uint32_t skip = ring_skip(ring_pos, np, RING); + if (skip) { + cbw(CB_W, skip * PAGE_TILES); + cb_pop_front(CB_W, skip * PAGE_TILES); + ring_pos += skip; + } + cbw(CB_W, np * PAGE_TILES); + pf_mark(2); +} +NOINL void w_pop(uint32_t np) { + cb_pop_front(CB_W, np * PAGE_TILES); + ring_pos += np; +} + +// ---------------------------------------------------------------- layer context +struct LC { + uint32_t l, op, flags, s, ct, kc, nkb, n, nbw, nbi, nres, nbias, bandp, pxb, u, boff; +}; +NOINL void lc_of(uint32_t l, LC& c) { + c.l = l; + c.op = pl.lf(l, L_OP); + c.flags = pl.lf(l, L_FLAGS); + c.s = pl.lf(l, L_S); + c.ct = pl.lf(l, L_CT); + c.kc = pl.lf(l, L_KC); + c.nkb = pl.lf(l, L_NKB); + c.n = pl.lf(l, L_N); + c.nbw = pl.lf(l, L_NBW); + c.nbi = pl.lf(l, L_NBI); + c.nres = pl.lf(l, L_NRES); + c.nbias = pl.lf(l, L_NBIAS); + c.bandp = pl.lf(l, L_BANDP); + c.pxb = c.ct * 64; // bytes per pixel of the input map (C3 / UP / HC) + c.u = pl.lf(l, L_U); + c.boff = pl.lf(l, L_BOFF); // C3 / HC: band row data (x = -1) behind the left edge chunk slack +} + +// ---------------------------------------------------------------- epilogues / 1x1 passes (templated pack-untilize) +template +NOINL void epi_untilize(uint32_t mt, bool relu) { + cbw(CB_ACC, ACC_CAP); + reconfig_data_format_srca(CB_ACC); + copy_init(CB_ACC); + PACK((llk_pack_reconfig_l1_acc(0))); + pack_untilize_dest_init(CB_OUT); + if (relu) { + relu_on(); + } + for (uint32_t m = 0; m < mt; ++m) { + cbr(CB_OUT, OUT_BLK); + for (uint32_t b = 0; b < NBW / NS; ++b) { + tile_regs_acquire(); + for (uint32_t i = 0; i < NS; ++i) { + copy_tile(CB_ACC, m * NBW + b * NS + i, i); + } + tile_regs_commit(); + tile_regs_wait(); + pack_untilize_dest(CB_OUT, 1, b); + tile_regs_release(); + } + cb_push_back(CB_OUT, OUT_BLK); + } + if (relu) { + relu_off(); + } + pack_untilize_uninit(CB_OUT); + cb_pop_front(CB_ACC, ACC_CAP); +} +NOINL void epi_untilize_n(uint32_t nbw, uint32_t mt, bool relu) { + switch (nbw) { + case 1: epi_untilize<1, 1>(mt, relu); break; + case 2: epi_untilize<2, 2>(mt, relu); break; + case 4: epi_untilize<4, 4>(mt, relu); break; + default: epi_untilize<4, 8>(mt, relu); break; + } +} + +// per-pixel matmul (UP / RA), output tile (m, n) = E01 bias(n) [nbias] + sum_cc A[m * astride + a0 + cc] W(cc, n), +// packed into the fp32 accumulators (l1acc from the second k-block on); epi_untilize writes CB_OUT +NOINL void mm1x1_acc(uint32_t in0, uint32_t mt, uint32_t astride, uint32_t a0, uint32_t kc, uint32_t nbias, + uint32_t nbw, uint32_t l1acc) { + const uint32_t ns = nbw < 4 ? nbw : 4; + mm_init_f(in0, CB_W); + pk(CB_ACC, l1acc); + for (uint32_t m = 0; m < mt; ++m) { + for (uint32_t n0 = 0; n0 < nbw; n0 += ns) { + tile_regs_acquire(); + for (uint32_t i = 0; i < ns; ++i) { + const uint32_t n = n0 + i; + if (nbias) { + mm_f(CB_CONST, CB_W, C_E01, n, i); + } + for (uint32_t cc = 0; cc < kc; ++cc) { + mm_f(in0, CB_W, m * astride + a0 + cc, nbias + cc * nbw + n, i); + } + } + tile_regs_commit(); + tile_regs_wait(); + for (uint32_t i = 0; i < ns; ++i) { + pack_tile(i, CB_ACC, m * nbw + n0 + i); + } + tile_regs_release(); + } + } +} + +// ---------------------------------------------------------------- C3 / HC +ALWI uint32_t aidx(uint32_t dxi, uint32_t j, uint32_t kx, uint32_t cc, uint32_t rows, uint32_t bw, uint32_t kc) { + return ((dxi * rows + j) * bw + kx) * kc + cc; +} + +// residual map -> accumulators (first overwrites, second accumulates): the unit's tiles (r, kx, n) of the CB_RES band +// are tilized (bf16, CB_A as scratch, chunks of whole M tiles) and copied through DST into the fp32 CB_ACC +NOINL void res_add(const LC& c, const Unit& un, uint32_t ri, uint32_t bwmax) { + cbw(CB_RES, 1); + const uint32_t r16 = rd16(CB_RES); + const uint32_t n = c.n, mt = un.bh * un.bw; + const uint32_t pitch16 = 32 * bwmax * n * 4; // 32 BW pixels x n tiles x 64 B, in 16 B + const uint32_t per = (A_CAP - 1) / n; // M tiles per chunk + for (uint32_t m0 = 0; m0 < mt; m0 += per) { + const uint32_t m1 = m0 + per < mt ? m0 + per : mt; + ft_begin(CB_RES, n, CB_A, false); + cbr(CB_A, A_CAP); + for (uint32_t m = m0; m < m1; ++m) { + const uint32_t r = m / un.bw, kx = m - r * un.bw; + ft_run(CB_RES, r16 + r * pitch16 + kx * 32 * n * 4, n, n, CB_A, (m - m0) * n); + } + cb_push_back(CB_A, A_CAP); + ft_end(CB_RES, CB_A, n, false); + cbw(CB_A, A_CAP); + reconfig_data_format_srca(CB_A); + copy_init(CB_A); + pk(CB_ACC, ri > 0 ? 1 : 0); + for (uint32_t m = m0; m < m1; ++m) { + for (uint32_t n0 = 0; n0 < n; n0 += 4) { + const uint32_t ns = n - n0 < 4 ? n - n0 : 4; + tile_regs_acquire(); + for (uint32_t i = 0; i < ns; ++i) { + copy_tile(CB_A, (m - m0) * n + n0 + i, i); + } + tile_regs_commit(); + tile_regs_wait(); + for (uint32_t i = 0; i < ns; ++i) { + pack_tile(i, CB_ACC, m * c.nbw + n0 + i); + } + tile_regs_release(); + } + } + cb_pop_front(CB_A, A_CAP); + } + cb_pop_front(CB_RES, 1); +} + +// k-block kb of the band -> A tiles: version (dx + 1, band row j, tile kx, channel tile cc) +NOINL void c3_tilize(const LC& c, const Unit& un, uint32_t kb, uint32_t b16, uint32_t ntz) { + const uint32_t rows = c.s * (un.bh - 1) + 3; + const bool relu = (c.flags & F_RELU_IN) != 0; + const uint32_t pitch = c.s * c.ct; + ft_begin(CB_BAND, pitch, CB_A, relu); + cbr(CB_A, A_CAP); + const uint32_t px16 = c.pxb >> 4; + for (uint32_t dxi = 0; dxi < 3; ++dxi) { + for (uint32_t j = 0; j < rows; ++j) { + for (uint32_t kx = 0; kx < un.bw; ++kx) { + const uint32_t src16 = b16 + j * (c.bandp >> 4) + (c.s * 32 * kx + dxi) * px16 + kb * c.kc * 4; + ft_run(CB_BAND, src16, ntz, pitch, CB_A, aidx(dxi, j, kx, 0, rows, un.bw, ntz)); + } + } + } + cb_push_back(CB_A, A_CAP); + ft_end(CB_BAND, CB_A, pitch, relu); + pf_mark(4); +} + +// akc: channel tiles per A version (the tilized k-block, 2 in pair mode), coff: this k-block's first of them +NOINL void c3_pass(const LC& c, const Unit& un, uint32_t kb, uint32_t akc, uint32_t coff, bool pop) { + const uint32_t rows = c.s * (un.bh - 1) + 3, bw = un.bw, kc = c.kc, nbw = c.nbw, s = c.s; + const uint32_t ns = nbw < 4 ? nbw : 4; + const bool hc = c.op == OP_HC; + const uint32_t off = kb == 0 ? c.nbias : 0; + cbw(CB_A, A_CAP); + mm_init_f(CB_A, CB_W); + pk(CB_ACC, (kb > 0 || c.nres > 0) ? 1 : 0); + for (uint32_t r = 0; r < un.bh; ++r) { + for (uint32_t kx = 0; kx < bw; ++kx) { + const uint32_t m = r * bw + kx; + for (uint32_t n0 = 0; n0 < nbw; n0 += ns) { + tile_regs_acquire(); + for (uint32_t i = 0; i < ns; ++i) { + const uint32_t n = n0 + i; + if (kb == 0) { + if (hc) { + mm_f(CB_SEL, CB_W, m, n, i); + } else { + mm_f(CB_CONST, CB_W, C_E01, n, i); + } + } + for (uint32_t cc = 0; cc < kc; ++cc) { + if (hc) { + const uint32_t a_ = n >> 1, b_ = n & 1; + for (uint32_t o = 0; o < 4; ++o) { + const uint32_t j = r + a_ + (o >> 1); // r + 1 + oy, oy = a - 1 + (o >> 1) + const uint32_t dxi = b_ + (o & 1); // ox + 1 + mm_f(CB_A, CB_W, aidx(dxi, j, kx, cc + coff, rows, bw, akc), off + (cc * 4 + n) * 4 + o, i); + } + } else { + for (uint32_t t = 0; t < 9; ++t) { + const uint32_t j = s * r + t / 3; // s r + 1 + dy + mm_f(CB_A, CB_W, aidx(t % 3, j, kx, cc + coff, rows, bw, akc), off + (cc * 9 + t) * nbw + n, + i); + } + } + } + } + tile_regs_commit(); + tile_regs_wait(); + for (uint32_t i = 0; i < ns; ++i) { + pack_tile(i, CB_ACC, m * nbw + n0 + i); + } + tile_regs_release(); + } + } + } + if (pop) { + cb_pop_front(CB_A, A_CAP); + } +} + +// HC epilogue: per M tile, relu(acc) -> Z (bf16, 4 sub-pixel tiles); R = sum_s (w4 hi + lo)_s Z_s^T + b4; relu +NOINL void epi_hc(uint32_t mt) { + cbw(CB_ACC, ACC_CAP); + for (uint32_t m0 = 0; m0 < mt; m0 += 4) { + const uint32_t nz = mt - m0 < 4 ? mt - m0 : 4; + reconfig_data_format_srca(CB_ACC); + copy_init(CB_ACC); + pk(CB_Z, 0); + relu_on(); + cbr(CB_Z, Z_CAP); + for (uint32_t i = 0; i < nz; ++i) { + tile_regs_acquire(); + for (uint32_t sb = 0; sb < 4; ++sb) { + copy_tile(CB_ACC, (m0 + i) * 4 + sb, sb); + } + tile_regs_commit(); + tile_regs_wait(); + for (uint32_t sb = 0; sb < 4; ++sb) { + pack_tile(sb, CB_Z, i * 4 + sb); + } + tile_regs_release(); + } + cb_push_back(CB_Z, Z_CAP); + cbw(CB_Z, Z_CAP); + mm_init_n(CB_CONST, CB_Z, 1); + pk(CB_HO, 0); + for (uint32_t i = 0; i < nz; ++i) { + cbr(CB_HO, 1); + tile_regs_acquire(); + for (uint32_t sb = 0; sb < 4; ++sb) { + mm_f(CB_CONST, CB_Z, C_W4H + sb, i * 4 + sb, 0); + mm_f(CB_CONST, CB_Z, C_W4L + sb, i * 4 + sb, 0); + } + mm_f(CB_CONST, CB_CONST, C_E4, C_B4T, 0); + tile_regs_commit(); + tile_regs_wait(); + pack_tile(0, CB_HO); + tile_regs_release(); + cb_push_back(CB_HO, 1); + } + relu_off(); + cb_pop_front(CB_Z, Z_CAP); + } + cb_pop_front(CB_ACC, ACC_CAP); +} + +// ---------------------------------------------------------------- layer +NOINL void run_layer(uint32_t l, uint32_t x, uint32_t y) { + LC c; + lc_of(l, c); + pf_start(l); + Sched sc; + sched_of(pl, l, x, y, sc); + const uint32_t bp0 = pl.lf(l, L_BP0), bp = pl.lf(l, L_BP); + for (uint32_t gi = 0; gi < sc.ng; ++gi) { + for (uint32_t k = 0; k < sc.rounds; ++k) { + const uint32_t u = k * sc.span + sc.off; + const bool valid = u < c.u; + if (c.op == OP_RA) { + uint32_t m0 = 0, mt = 0; + if (valid) { + ra_unit(pl, l, u, m0, mt); + pf_mark(5); + cbw(CB_TAPA, TAPA_CAP); + pf_mark(3); + } + for (uint32_t nbi = 0; nbi < c.nbi; ++nbi) { + if (valid) { + cbr(CB_ACC, ACC_CAP); + } + for (uint32_t kb = 0; kb < c.nkb; ++kb) { + const uint32_t np = kb == 0 ? bp0 : bp; + w_wait(np); + if (valid) { + mm1x1_acc(CB_TAPA, mt, c.ct, kb * c.kc, c.kc, kb == 0 ? c.nbias : 0, c.nbw, kb > 0 ? 1 : 0); + } + w_pop(np); + } + if (valid) { + cb_push_back(CB_ACC, ACC_CAP); + epi_untilize_n(c.nbw, mt, false); + } + } + if (valid) { + cb_pop_front(CB_TAPA, TAPA_CAP); + } + continue; + } + Unit un; + if (valid) { + unit_of(pl, l, u, un); + } + if (c.op == OP_UP) { + const uint32_t mt = valid ? un.bh * un.bw : 0; + if (valid) { + pf_mark(5); + cbw(CB_BAND, 1); + pf_mark(3); + const uint32_t b16 = rd16(CB_BAND); + ft_begin(CB_BAND, c.ct, CB_A, false); + cbr(CB_A, A_CAP); + for (uint32_t r = 0; r < un.bh; ++r) { + for (uint32_t kx = 0; kx < un.bw; ++kx) { + const uint32_t src16 = b16 + r * (c.bandp >> 4) + kx * 32 * (c.pxb >> 4); + ft_run(CB_BAND, src16, c.ct, c.ct, CB_A, (r * un.bw + kx) * c.ct); + } + } + cb_push_back(CB_A, A_CAP); + ft_end(CB_BAND, CB_A, c.ct, false); + cb_pop_front(CB_BAND, 1); + pf_mark(4); + cbw(CB_A, A_CAP); + } + for (uint32_t nbi = 0; nbi < c.nbi; ++nbi) { + w_wait(bp0); + if (valid) { + cbr(CB_ACC, ACC_CAP); + mm1x1_acc(CB_A, mt, c.ct, 0, c.kc, c.nbias, c.nbw, 0); + } + w_pop(bp0); + if (valid) { + cb_push_back(CB_ACC, ACC_CAP); + epi_untilize_n(c.nbw, mt, false); + } + } + if (valid) { + cb_pop_front(CB_A, A_CAP); + } + continue; + } + // C3 / HC: n-blocks nbi of this group (nbi > 1 only for C3 without residuals: whole output pixels of the + // unit on one core, the BRISC stages them in L1 and writes whole pages); the band stays for every n-block + const uint32_t bwmax = pl.lf(l, L_BW); + uint32_t b16 = 0; + const bool pair = pl.lf(l, L_PAIR) != 0; + for (uint32_t nbi = 0; nbi < c.nbi; ++nbi) { + if (valid) { + cbr(CB_ACC, ACC_CAP); + if (nbi == 0) { + for (uint32_t ri = 0; ri < c.nres; ++ri) { + res_add(c, un, ri, bwmax); + } + pf_mark(4); + cbw(CB_BAND, 1); + pf_mark(3); + b16 = rd16(CB_BAND) + (c.boff >> 4); + if (c.op == OP_HC) { + cbw(CB_SEL, SEL_CAP); + } + } + } + for (uint32_t kb = 0; kb < c.nkb; ++kb) { + const uint32_t np = kb == 0 ? bp0 : bp; + w_wait(np); + if (valid) { + if (!pair || (kb & 1) == 0) { + c3_tilize(c, un, kb, b16, pair ? 2 : c.kc); + } + c3_pass(c, un, kb, pair ? 2 : c.kc, pair ? (kb & 1) : 0, !pair || (kb & 1) == 1); + } + w_pop(np); + } + if (valid) { + if (nbi + 1 == c.nbi) { + cb_pop_front(CB_BAND, 1); + } + cb_push_back(CB_ACC, ACC_CAP); + pf_mark(5); + if (c.op == OP_HC) { + cb_pop_front(CB_SEL, SEL_CAP); + epi_hc(un.bh * un.bw); + } else { + epi_untilize_n(c.nbw, un.bh * un.bw, (c.flags & F_RELU_OUT) != 0); + } + pf_mark(6); + } + } + } + } +} + +} // namespace + +void kernel_main() { + const uint32_t x = get_arg_val(A_X), y = get_arg_val(A_Y); + uint32_t nl = get_common_arg_val(K_NL); + g_spin = get_common_arg_val(K_SPIN); + g_sync = cb_addr(CB_SYNC); + compute_kernel_hw_startup(CB_A, CB_W, CB_ACC); + wait_plan_all(); + RING = pl.hdr(H_RING); + if (nl > pl.hdr(H_NL)) { + nl = pl.hdr(H_NL); + } + cbw(CB_CONST, N_CONST); + const uint32_t ngrp = pl.hdr(H_NGRP); + for (uint32_t grp = 0; grp < ngrp; ++grp) { + for (uint32_t l = 0; l < nl; ++l) { + run_layer(l, x, y); + pf_mark(5); + } + } +} diff --git a/code/tt_depthpro2/tt/mk_dec/plan.py b/code/tt_depthpro2/tt/mk_dec/plan.py new file mode 100644 index 0000000000000000000000000000000000000000..866b9bd793c1b4023291dcbf55278bc7fd82c6b9 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_dec/plan.py @@ -0,0 +1,693 @@ +# SPDX-License-Identifier: Apache-2.0 +"""DEC megakernel plan (host mirror of ``kernels/md_defs.hpp`` + the plan table in the compile-time args). + +Feature maps live in DRAM as ROW_MAJOR NHWC "padded raster" storage (see :class:`MapG`): every image row has one +zero pad pixel after it (pitch ``W' = W + 1``), there is a zero guard row above and below the image and the pads / +guards are zero-initialized once and never written. A 3x3 tap ``(dy, dx)`` of 32 consecutive output pixels of one +image row is then 32 consecutive storage pixels (the x borders read pad pixels = the zero padding), so the A +operand of every tap is a contiguous ROW_MAJOR run that the TRISC tilizes straight out of the unit's L1 band. + +Layers (one barrier-separated phase each; the whole list runs once per frame group of ``G`` frames): + +* ``RA`` reassemble.i.0 (1x1) on the tapped tokens (TILE) -> map; +* ``UP`` conv-transpose k x k stride k (reassemble.0.1 k=4, reassemble.1.1 k=2, the fusion deconv with the 1x1 + out_conv folded in) = per-pixel matmul with N ordered (a, b, c) + depth-to-space writes; +* ``C3`` 3x3 conv (stride 1, or 2 for reassemble.3.1) with optional input ReLU (applied by the packer when the + input is tilized), output ReLU, bias and up to two residual maps (added in fp32 before the single bf16 rounding); +* ``HC`` head.1 (convT k2s2) o head.2 (3x3) folded into one 3x3 conv on the half-resolution map with 4 sub-pixel + output tiles (each uses 4 of the 9 half-res neighbours), + bias (per-pixel class: head.1's bias does not pass the + zero padding), ReLU, head.4 (1x1, 32 -> 1) + ReLU -> the float32 inverse depth (TILE). + +Work decomposition of a layer: units (2D blocks of BH output rows x BW tiles of 32 pixels; RA: BH token tiles) x +n-blocks (NBW output tiles). The n-blocks form NBO groups (split over groups of grid rows) of NBI blocks (iterated +inside a unit). Every grid row shares one weight stream (the row feeder multicasts it); a row group's cores take +the group's units round-robin, one unit per core per round, and every core of the row consumes the stream once +per round. +""" + +from __future__ import annotations + +import math +import os +import re +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence, Tuple + +KDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels") +DEFS_PATH = os.path.join(KDIR, "md_defs.hpp") + + +def _parse_defs(path: str = DEFS_PATH) -> Dict[str, int]: + out = {} + pat = re.compile(r"^\s*constexpr\s+uint32_t\s+([A-Z0-9_]+)\s*=\s*([0-9]+)\s*;") + with open(path) as f: + for line in f: + m = pat.match(line) + if m: + out[m.group(1)] = int(m.group(2)) + return out + + +D = _parse_defs() +globals().update(D) + +NONE = 0xFFFF +#: reference model dims (reference/model.py SIZES) +DIMS = {"S": ((48, 96, 192, 384), 64, 384), "B": ((96, 192, 384, 768), 128, 768), + "L": ((256, 512, 1024, 1024), 256, 1024), "H": ((256, 512, 1024, 1024), 256, 1280)} + +#: L1 caps per CB (bytes); the program allocates exactly the max over layers (<= cap) +CAPS = dict(band=400 << 10, a=160 << 10, res=136 << 10, acc=256 << 10, sel=32 << 10) +RING_PAGES = 20 +FEED_BW = float(os.environ.get("DEPTHPRO2_MK_DEC_FEED_GBS", "16")) * 1e9 # bytes / s per row feeder +#: opt-in (not yet cleared on the device, MK_LOG round 3): narrow n-blocks for weight-heavy layers split over row +#: groups, UP n-block groups over row groups, feeder bandwidth in the cost model +NSPLIT = os.environ.get("DEPTHPRO2_MK_DEC_NSPLIT", "0") == "1" +BLK_MAX = RING_PAGES * PAGE_TILES // 2 # tiles per weight block (double-buffered ring) +L1_BUDGET = 1400 * 1024 + + +def c32(n: int) -> int: + return -(-n // 32) * 32 + + +def cdiv(a: int, b: int) -> int: + return -(-a // b) + + +def pow2_div(n: int, cap: int = 8) -> int: + """largest power of two <= cap dividing n""" + p = 1 + while p * 2 <= cap and n % (p * 2) == 0: + p *= 2 + return p + + +@dataclass +class MapG: + """Padded-raster ROW_MAJOR storage of an H x W x C map (``frames`` frames). Storage pixel of (y, x) = + ``b0 + y * wp + x`` for y in [-1, H], x in [-1, W] (x = -1 / W fall into the zero pad columns [W, wp), y = -1 / H + are the zero guard rows); a DRAM page holds 32 storage pixels x C channels (>= 2 KB). ``wp`` and ``b0`` are + multiples of 32, so every image row starts on a page: a unit's tile columns are whole pages (DRAM requests >= 2 KB, + Blackhole SYS-1419).""" + + name: str + H: int + W: int + C: int + frames: int = 1 + idx: int = -1 + + @property + def wp(self) -> int: + return c32(self.W + 1) + + @property + def b0(self) -> int: + return self.wp + 32 # guard row -1 plus one page in front of it (left edge chunk of row -1) + + @property + def fpix(self) -> int: + return c32(self.b0 + (self.H + 3) * self.wp + 64) # rows -1 .. H, one overshoot row, edge chunks + + @property + def fpg(self) -> int: + return self.fpix // 32 + + @property + def page_bytes(self) -> int: + return 64 * self.C + + @property + def pages(self) -> int: + return self.frames * self.fpg + + @property + def bytes(self) -> int: + return self.pages * self.page_bytes + + def g(self, y: int, x: int) -> int: + return self.b0 + y * self.wp + x + + +@dataclass +class Layer: + op: int + name: str + src: int # map id (RA: tap index) + dst: int # map id (HC: -1) + res: Tuple[int, ...] = () + flags: int = 0 + s: int = 1 # C3 stride / UP k + cin: int = 0 # input channels (padded) + n: int = 0 # output tiles + # weight keys (wprep) + wkey: str = "" + # chosen config + kc: int = 0 + nkb: int = 1 + nbw: int = 0 + nbo: int = 1 + nbi: int = 1 + bh: int = 1 + bw: int = 1 + yb: int = 1 + xb: int = 1 + u: int = 0 + ho: int = 0 + wo: int = 0 + kxo: int = 0 + bandp: int = 0 + boff: int = 0 # C3 / HC: byte offset of the band row data (x = -1) behind the left edge chunk slack + kpx: int = 1 # C3 / HC: pixels of one band edge chunk (>= 2 KB) + nbias: int = 0 + acc: int = 0 + wpg: int = 0 + bp0: int = 0 + bp: int = 0 + row0: int = 0 # grid rows [row0, row0 + nrows) run this layer (phase merging); 0 = all rows + nrows: int = 0 + bar: int = 1 # 1: global barrier after this layer (end of its phase) + est: Dict[str, float] = field(default_factory=dict) + + @property + def ct(self) -> int: + return self.cin // 32 + + +class Plan: + """Maps + layers + per-layer configs of one DEC program (size, T, hp, wp) on a ``gx x gy`` grid.""" + + def __init__(self, size: str, T: int, hp: int, wp: int, gx: int, gy: int, group: Optional[int] = None, + map_budget: Optional[int] = None, merge: Optional[bool] = None): + if hp % 32 or wp % 32: + raise ValueError("hp, wp must be multiples of 32") + self.size, self.T, self.hp, self.wp = size, T, hp, wp + self.C, self.R = gx, gy + self.NC = gx * gy + dr, d, cdim = DIMS[size] + self.dr = tuple(c32(v) for v in dr) + self.dr_raw = dr + self.d = d + self.cdim = cdim + self.gh, self.gw = hp // 16, wp // 16 + self.n = self.gh * self.gw + self.np_ = c32(self.n) + self.pt = self.np_ // 32 + budget = map_budget or int(os.environ.get("DEPTHPRO2_MK_DEC_MAP_MB", "1536")) << 20 + if group is None: + per = self._map_bytes(1) + group = 1 + for g in range(T, 0, -1): + if T % g == 0 and per * g <= budget: + group = g + break + if T % group: + raise ValueError("group must divide T") + self.G = group + self.ngrp = T // group + self.maps: List[MapG] = [] + self.layers: List[Layer] = [] + self._build() + for L in self.layers: + self._config(L) + if merge is None: + merge = os.environ.get("DEPTHPRO2_MK_DEC_MERGE", "0") == "1" + self.phases = self._phases() if merge else [[i] for i in range(len(self.layers))] + self.weight_pages = assign_pages(self.layers) + self.kx_hc = cdiv(self.wp // 2, 32) + + # ------------------------------------------------------------------ structure + def _map_bytes(self, frames: int) -> int: + saved = getattr(self, "maps", None) + self.maps = [] + self.layers = [] + self.G = frames + self._build() + b = sum(m.bytes for m in self.maps) + self.maps, self.layers = [], [] + return b + + def _map(self, name: str, H: int, W: int, C: int) -> int: + m = MapG(name, H, W, C, self.G, len(self.maps)) + self.maps.append(m) + return m.idx + + def _layer(self, **kw) -> Layer: + L = Layer(**kw) + self.layers.append(L) + return L + + def _build(self): + gh, gw, d = self.gh, self.gw, self.d + dr = self.dr + M = self._map + lv = {3: (gh // 2, gw // 2), 2: (gh, gw), 1: (2 * gh, 2 * gw), 0: (4 * gh, 4 * gw), -1: (8 * gh, 8 * gw)} + R0 = M("R0", gh, gw, dr[0]) + R1 = M("R1", gh, gw, dr[1]) + P2 = M("P2", gh, gw, dr[2]) + R3 = M("R3", gh, gw, dr[3]) + P0 = M("P0", *lv[0], dr[0]) + P1 = M("P1", *lv[1], dr[1]) + P3 = M("P3", *lv[3], dr[3]) + P = {0: P0, 1: P1, 2: P2, 3: P3} + Ls = self._layer + cd = self.cdim + for i, (src, dst) in enumerate(((0, R0), (1, R1), (2, P2), (3, R3))): + Ls(op=OP_RA, name=f"ra{i}", src=src, dst=dst, flags=F_BIAS, cin=cd, n=dr[i] // 32, + wkey=f"encoder.reassemble.{i}.0") + Ls(op=OP_UP, name="up0", src=R0, dst=P0, flags=F_BIAS, s=4, cin=dr[0], n=16 * dr[0] // 32, + wkey="encoder.reassemble.0.1") + Ls(op=OP_UP, name="up1", src=R1, dst=P1, flags=F_BIAS, s=2, cin=dr[1], n=4 * dr[1] // 32, + wkey="encoder.reassemble.1.1") + Ls(op=OP_C3, name="s2", src=R3, dst=P3, flags=F_BIAS, s=2, cin=dr[3], n=dr[3] // 32, + wkey="encoder.reassemble.3.1") + S, Tm, Y, Z, X = {}, {}, {}, {}, {} + for i in (3, 2, 1, 0): + H, W = lv[i] + S[i] = M(f"S{i}", H, W, d) + Tm[i] = M(f"T{i}", H, W, d) + Y[i] = M(f"Y{i}", H, W, d) + Z[i] = M(f"Z{i}", *lv[i - 1], d) + if i < 3: + X[i] = M(f"X{i}", H, W, d) + Hh = M("Hh", *lv[-1], d // 2) + fp = lambda i: f"decoder.fusions.{i}" # noqa: E731 + c1 = F_RELU_IN | F_RELU_OUT | F_BIAS + # order: independent layers adjacent (phase merging, _phases), then the serial fusion chain + Ls(op=OP_C3, name="cv2", src=P[2], dst=S[2], flags=0, cin=dr[2], n=d // 32, wkey="decoder.convs.2") + for i in (3, 1, 0): + Ls(op=OP_C3, name=f"cv{i}", src=P[i], dst=S[i], flags=0, cin=dr[i], n=d // 32, wkey=f"decoder.convs.{i}") + for i in (2, 1, 0): + Ls(op=OP_C3, name=f"f{i}r1c1", src=S[i], dst=Tm[i], flags=c1, cin=d, n=d // 32, + wkey=fp(i) + ".resnet1.residual.1") + for i in (3, 2, 1, 0): + x = S[3] + if i < 3: + Ls(op=OP_C3, name=f"f{i}r1c3", src=Tm[i], dst=X[i], res=(Z[i + 1], S[i]), flags=F_BIAS, cin=d, + n=d // 32, wkey=fp(i) + ".resnet1.residual.3") + x = X[i] + Ls(op=OP_C3, name=f"f{i}r2c1", src=x, dst=Tm[i], flags=c1, cin=d, n=d // 32, + wkey=fp(i) + ".resnet2.residual.1") + Ls(op=OP_C3, name=f"f{i}r2c3", src=Tm[i], dst=Y[i], res=(x,), flags=F_BIAS, cin=d, n=d // 32, + wkey=fp(i) + ".resnet2.residual.3") + Ls(op=OP_UP, name=f"f{i}up", src=Y[i], dst=Z[i], flags=F_BIAS, s=2, cin=d, n=4 * d // 32, wkey=fp(i) + ".up") + Ls(op=OP_C3, name="h0", src=Z[0], dst=Hh, flags=F_BIAS, cin=d, n=d // 64, wkey="head.0") + Ls(op=OP_HC, name="hc", src=Hh, dst=-1, flags=F_BIAS, cin=d // 2, n=4, wkey="head.hc") + + # ------------------------------------------------------------------ phases (layer merging) + def _phases(self) -> List[List[int]]: + """Consecutive independent layers (none reads or writes a map another one of the phase writes) share one + barrier-separated phase; each gets a contiguous slice of grid rows ~ its estimated time (>= 1 row).""" + phases: List[List[int]] = [] + cur: List[int] = [] + wr: set = set() + rd: set = set() + for i, L in enumerate(self.layers): + ins = set(L.res) | ({L.src} if L.op != OP_RA else set()) + outs = {L.dst} if L.dst >= 0 else set() + if cur and (ins & wr or outs & (wr | rd) or len(cur) >= self.R): + phases.append(cur) + cur, wr, rd = [], set(), set() + cur.append(i) + wr |= outs + rd |= ins + if cur: + phases.append(cur) + for ph in phases: + for i in ph: + self.layers[i].bar = 0 + self.layers[ph[-1]].bar = 1 + if len(ph) == 1: + continue + est = [max(self.layers[i].est.get("ms", 0.0), 1e-4) for i in ph] + rows = [1] * len(ph) + for _ in range(self.R - len(ph)): # greedy: give the next row to the slowest layer (time / rows) + j = max(range(len(ph)), key=lambda k: est[k] / rows[k]) + rows[j] += 1 + r0 = 0 + for i, nr in zip(ph, rows): + L = self.layers[i] + L.row0, L.nrows = r0, nr + r0 += nr + self._config(L) + return phases + + # ------------------------------------------------------------------ per-layer config + def _rows(self, L: Layer) -> int: + return L.nrows or self.R + + def _span(self, L: Layer) -> int: + """cores sharing a group's units""" + R = self._rows(L) + if L.nbo <= R: + return (R // L.nbo) * self.C + return self.C + + def _rounds(self, L: Layer) -> int: + R = self._rows(L) + rounds = cdiv(L.u, self._span(L)) + if L.nbo > R: + rounds *= cdiv(L.nbo, R) + return rounds + + def _config(self, L: Layer): + static_cfg(L) + src = self.maps[L.src] if L.op != OP_RA else None + if L.op == OP_RA: + self._cfg_ra(L) + elif L.op == OP_UP: + self._cfg_up(L, src) + else: + self._cfg_c3(L, src) + + def _cost(self, L: Layer, mm: int, tz: int, pk: int, nkb_tot: int, dram: int) -> float: + """cycles of one unit (compute) and bytes moved per unit""" + cyc = mm * 64 + tz * 70 + pk * 40 + nkb_tot * 1500 + 4000 + return cyc + + def _round_time(self, L: Layer, unit_cyc: float, unit_bytes: float, wbytes: float) -> float: + """seconds of one round of the whole grid: compute vs DRAM (all active cores)""" + R = self._rows(L) + active = min(R * self.C, L.u * L.nbo if L.nbo <= R else L.u * R) + comp = unit_cyc / 1.35e9 + dram = (unit_bytes * active + wbytes * R) / 380e9 + feed = wbytes / FEED_BW if NSPLIT else 0.0 # every row streams its blocks through one feeder (~11 GB/s) + return max(comp, dram, feed) + + def _cfg_ra(self, L: Layer): + """RA units are output map pages: (frame, token row y, page p) = tokens [y gw + 32 p, y gw + min(32 p + 32, gw)) + (<= 2 token tiles, mb = 2). One core computes every n-block of its unit (nbo = 1) into an L1 staging page + and writes the whole 32-pixel page (>= 2 KB DRAM write).""" + kt = self.cdim // 32 + n = L.n + nb = n // L.nbw + mb = 2 + if mb * kt * T16 > CAPS["band"] or mb * L.nbw * T32 > CAPS["acc"] or 32 * n * 64 > CAPS["res"]: + raise RuntimeError(f"no RA config for {L.name}") + npg = cdiv(self.gw, 32) + L.nbo, L.nbi, L.bh, L.bw = 1, nb, mb, 1 + L.u = self.G * self.gh * npg + L.kc, L.nkb, L.acc = L.kc, kt // L.kc, 1 + rounds = self._rounds(L) + mm = mb * kt * L.nbw * nb + mb * L.nbw * nb + cyc = self._cost(L, mm, 0, mb * L.nbw * nb * (L.nkb + 1), L.nkb * nb, 0) + ub = mb * kt * T16 + 32 * n * 64 + wb = (kt * L.nbw + L.nbw) * nb * T16 + t = rounds * self._round_time(L, cyc, ub, wb) + L.yb, L.xb = L.u, 1 + L.ho, L.wo, L.kxo = self.gh, self.gw, self.pt + L.nbias = L.nbw + L.est = {"ms": t * 1e3, "rounds": rounds} + L.cin = self.cdim + + def _cfg_up(self, L: Layer, src: MapG): + ct = L.ct + H, W = src.H, src.W + kx = cdiv(W, 32) + nbw = L.nbw + nb = L.n // nbw + L.acc = 1 + best = None + k = L.s + cout = L.n * 32 // (k * k) + nbpa = (k * cout // 32) // nbw # n-blocks of one output a-row (whole output pages once all have landed) + if (k * cout // 32) % nbw: + raise RuntimeError(f"{L.name}: n-block {nbw} tiles does not divide an output row ({k * cout} channels)") + for nbo in ([v for v in range(1, nb + 1) if nb % v == 0] if NSPLIT else [1]): + nbi = nb // nbo + if nbi % nbpa: + continue + for bh in (1, 2, 4, 8, 16): + for bw in (1, 2, 3, 4, 6, 8): + if bw > kx or bh > H: + continue + band = bh * 32 * bw * src.C * 2 + stage = bh * bw * k * 32 * cout * 2 # one a-row of every (r, kx) of the unit, L1 staging + if (band > CAPS["band"] or bh * bw * ct * T16 > CAPS["a"] + or bh * bw * nbw * T32 > CAPS["acc"] or stage > CAPS["res"]): + continue + L.nbo, L.nbi = nbo, nbi + L.bh, L.bw = bh, bw + L.yb, L.xb = cdiv(H, bh), cdiv(kx, bw) + L.u = self.G * L.yb * L.xb + rounds = self._rounds(L) + mt = bh * bw + mm = mt * (ct + 1) * nbw * nbi + cyc = self._cost(L, mm, mt * ct, mt * nbw * nbi, nbi, 0) + ub = band + mt * 32 * nbw * nbi * 64 + wb = (ct + 1) * nbw * nbi * T16 + t = rounds * self._round_time(L, cyc, ub, wb) + key = (t, -mt, nbo) + if best is None or key < best[0]: + best = (key, (bh, bw, t, nbo, nbi)) + if best is None: + raise RuntimeError(f"no UP config for {L.name}") + L.bh, L.bw, t, L.nbo, L.nbi = best[1] + L.yb, L.xb = cdiv(H, L.bh), cdiv(kx, L.bw) + L.u = self.G * L.yb * L.xb + L.ho, L.wo, L.kxo = H, W, kx + L.bandp = 32 * L.bw * src.C * 2 + L.nbias = L.nbw + L.est = {"ms": t * 1e3, "rounds": self._rounds(L)} + + def _cfg_c3(self, L: Layer, src: MapG): + ct, s = L.ct, L.s + if L.op == OP_HC: + Ho, Wo = src.H, src.W + ntap = 16 # 4 sub-pixels x 4 neighbours (per output tile: 4 x ct) + else: + Ho, Wo = (src.H // s, src.W // s) + ntap = 9 + nbw = L.nbw + nb = L.n // nbw + kxo = cdiv(Wo, 32) + nres = len(L.res) + pxb = src.C * 2 + # band rows: [left edge chunk slack (kpx - 1 px)] x = -1, 32 s bw pixels (whole pages), [right edge chunk] + kpx = min(32, cdiv(MIN_REQ, pxb)) + if L.op == OP_HC and Ho % 8: + raise RuntimeError(f"{L.name}: HC needs a multiple of 8 rows ({Ho})") + best = None + for kc in (L.kc,): + nkb = ct // kc + for nbo in [v for v in range(1, nb + 1) if nb % v == 0]: + nbi = nb // nbo + if nbw < L.n and L.op == OP_C3 and not nres: + if nbo != 1: # whole output pixels on one core (L1 staging, whole-page writes) + continue + elif nbi != 1: + continue + for bh in ((8,) if L.op == OP_HC else (1, 2, 3, 4, 6, 8)): + for bw in (1, 2, 3, 4, 6, 8): + if bw > kxo or bh > Ho: + continue + rows = s * (bh - 1) + 3 + bandp = c16((s * 32 * bw + (2 * kpx if s == 1 else kpx)) * pxb) + band = rows * bandp + stage = bh * bw * 32 * L.n * 64 if nbi > 1 else (bw * 4096 if L.op == OP_HC else 0) + # kc == 1 out of a wider row: the k-block pair (kb, kb + 1) is tilized at once (2-tile + # fast-tilize chunks, the kernel keeps the A tiles over the two k-blocks: L1 "pair" mode) + a_t = 3 * rows * bw * (2 if pair_mode(L) else kc) + acc_t = bh * bw * nbw + sel_t = bh * bw if L.op == OP_HC else 0 + res_b = bh * 32 * bw * L.n * 64 if nres else 0 + if (band > CAPS["band"] or a_t * T16 > CAPS["a"] or acc_t * T32 > CAPS["acc"] + or res_b > CAPS["res"] or sel_t * T16 > CAPS["sel"] or stage > CAPS["res"]): + continue + L.nbo, L.nbi = nbo, nbi + L.u = self.G * cdiv(Ho, bh) * cdiv(kxo, bw) + rounds = self._rounds(L) + mt = bh * bw + kpt = (ntap * ct if L.op != OP_HC else 4 * ct) + mm = mt * nbw * (kpt + 1) * nbi + if L.op == OP_HC: + mm += mt * 9 + tz = a_t * (nkb // 2 if pair_mode(L) else nkb) * nbi + mt * nbw * nres + pk = mt * nbw * (nkb + 2) * nbi + cyc = self._cost(L, mm, tz, pk, nkb * nbi, 0) + ub = band + res_b + mt * 32 * nbw * 64 * nbi * (1 if L.op != OP_HC else 0) + wb = (kpt * nbw + nbw) * T16 * nbi + t = rounds * self._round_time(L, cyc, ub, wb) + key = (t, -mt, -kc) + if best is None or key < best[0]: + best = (key, dict(kc=kc, nkb=nkb, nbo=nbo, nbi=nbi, bh=bh, bw=bw, bandp=bandp, t=t)) + if best is None: + raise RuntimeError(f"no C3 config for {L.name} (cin {L.cin}, n {L.n}, map {src.H}x{src.W})") + c = best[1] + L.kc, L.nkb, L.nbo, L.nbi, L.bh, L.bw, L.bandp = c["kc"], c["nkb"], c["nbo"], c["nbi"], c["bh"], c["bw"], c["bandp"] + L.kpx, L.boff = kpx, (kpx - 1) * pxb + L.ho, L.wo, L.kxo = Ho, Wo, kxo + L.yb, L.xb = cdiv(Ho, L.bh), cdiv(kxo, L.bw) + L.u = self.G * L.yb * L.xb + L.acc = 1 + L.nbias = nbw if L.op != OP_HC else 4 + L.est = {"ms": c["t"] * 1e3, "rounds": self._rounds(L)} + + # ------------------------------------------------------------------ L1 + def cb_sizes(self) -> Dict[str, int]: + band = a = res = acc = sel = 0 + for L in self.layers: + res = max(res, stage_bytes(L)) # L1 staging of whole-page outputs lives in the CB_RES memory + if L.op == OP_RA: + band = max(band, L.bh * L.cin // 32 * T16) + acc = max(acc, L.bh * L.nbw * T32) + continue + src = self.maps[L.src] + if L.op == OP_UP: + band = max(band, L.bh * L.bandp) + a = max(a, L.bh * L.bw * L.ct * T16) + acc = max(acc, L.bh * L.bw * L.nbw * T32) + continue + rows = L.s * (L.bh - 1) + 3 + band = max(band, rows * L.bandp) + a = max(a, 3 * rows * L.bw * (2 if pair_mode(L) else L.kc) * T16) + acc = max(acc, L.bh * L.bw * L.nbw * T32) + if L.res: + res = max(res, L.bh * 32 * L.bw * L.n * 64) + if L.op == OP_HC: + sel = max(sel, L.bh * L.bw * T16) + return dict(w=RING_PAGES * PAGE_TILES * T16, band=c16(band), a=max(a, T16), res=c16(max(res, 16)), + acc=max(acc, T32), out=OUT_CAP * T16, const=N_CONST * T16, sel=max(sel, T16), z=4 * T16, + ho=2 * T32, sync=SYNC_BYTES) + + def l1_bytes(self) -> int: + return sum(self.cb_sizes().values()) + + # ------------------------------------------------------------------ serialization + def table(self) -> List[int]: + hdr = [0] * NHF + hdr[H_NL] = len(self.layers) + hdr[H_NM] = len(self.maps) + hdr[H_G] = self.G + hdr[H_NGRP] = self.ngrp + hdr[H_PT] = self.pt + hdr[H_N] = self.n + hdr[H_GW] = self.gw + hdr[H_HP] = self.hp + hdr[H_WP] = self.wp + hdr[H_RING] = RING_PAGES + hdr[H_KX_HC] = self.kx_hc + out = list(hdr) + for m in self.maps: + f = [0] * NMF + f[M_H], f[M_W], f[M_WP], f[M_C], f[M_B0], f[M_FPG], f[M_ARG] = m.H, m.W, m.wp, m.C, m.b0, m.fpg, K_MAP0 + m.idx + out += f + for L in self.layers: + f = [0] * NLF + f[L_OP], f[L_SRC], f[L_DST] = L.op, L.src, (L.dst if L.dst >= 0 else NONE) + f[L_RES0] = L.res[0] if len(L.res) > 0 else NONE + f[L_RES1] = L.res[1] if len(L.res) > 1 else NONE + f[L_NRES], f[L_FLAGS], f[L_S] = len(L.res), L.flags, L.s + f[L_CT] = L.cin // 32 + f[L_KC], f[L_NKB], f[L_N], f[L_NBW], f[L_NBO], f[L_NBI] = L.kc, L.nkb, L.n, L.nbw, L.nbo, L.nbi + f[L_BH], f[L_BW], f[L_YB], f[L_XB], f[L_U] = L.bh, L.bw, L.yb, L.xb, L.u + f[L_WPG], f[L_BP0], f[L_BP] = L.wpg, L.bp0, L.bp + f[L_HO], f[L_WO], f[L_KXO], f[L_BANDP], f[L_NBIAS], f[L_ACC] = L.ho, L.wo, L.kxo, L.bandp, L.nbias, L.acc + f[L_ROW0], f[L_NROWS], f[L_BAR] = L.row0, L.nrows or self.R, L.bar + f[L_PAIR] = 1 if pair_mode(L) else 0 + f[L_BOFF], f[L_KPX] = L.boff, L.kpx + out += f + return out + + def summary(self) -> str: + lines = [f"plan {self.size} T={self.T} {self.hp}x{self.wp} grid {self.C}x{self.R} G={self.G} groups={self.ngrp} " + f"phases={len(self.phases)}"] + tot = 0.0 + for L in self.layers: + tot += L.est.get("ms", 0) * self.ngrp + lines.append(f" {L.name:7s} op{L.op} cin {L.cin:5d} n {L.n:3d} nbw {L.nbw} nbo {L.nbo} nbi {L.nbi} " + f"kc {L.kc:2d} nkb {L.nkb:2d} bh {L.bh} bw {L.bw} u {L.u:5d} rows {L.row0}+{L.nrows or self.R} " + f"bar {L.bar} rounds {L.est.get('rounds')} " + f"est {L.est.get('ms', 0):.3f} ms") + sz = self.cb_sizes() + lines.append(f" est total {tot:.2f} ms; L1 {sum(sz.values()) / 1024:.0f} KB {{{', '.join(f'{k} {v // 1024}' for k, v in sz.items())}}}; " + f"maps {sum(m.bytes for m in self.maps) / 2**20:.0f} MB") + return "\n".join(lines) + + +def c16(n: int) -> int: + return -(-n // 16) * 16 + + +def _divs(n: int) -> List[int]: + return [k for k in range(n, 0, -1) if n % k == 0] + + +def static_cfg(L: Layer) -> None: + """Shape-independent stream parameters (k-block width kc, n-block width nbw, bias tiles): the weight arena of a + size is shared by every bucket / clip length. Canonical tile order of a k-block (after nbias bias tiles in + k-block 0): C3 (c, tap, n), HC (c, sub, neighbour), UP / RA (c, n).""" + ct = L.cin // 32 + if L.op == OP_RA: + L.nbw = pow2_div(L.n) + L.kc = next(k for k in _divs(ct) if k * L.nbw + L.nbw <= BLK_MAX) + elif L.op == OP_UP: + row = L.n // L.s # tiles of one output row a (k * cout channels); n-blocks never straddle two a-rows + nbw = pow2_div(row) + while ct * nbw + nbw > BLK_MAX and nbw > 1: + nbw //= 2 + L.nbw, L.kc = nbw, ct + elif L.op == OP_HC: + L.nbw = 4 + L.kc = next(k for k in _divs(ct) if k <= 3 and 16 * k + 4 <= BLK_MAX) + else: + L.nbw = pow2_div(L.n) + if NSPLIT and L.cin >= 384: # weight-heavy: n-blocks <= 2 tiles split over row groups (rows stream 1 / nb) + L.nbw = max(1, min(L.nbw, 2) if L.cin >= 768 else L.nbw // 2) + L.kc = next(k for k in _divs(ct) if k <= 3 and 9 * k * L.nbw + L.nbw <= BLK_MAX) + L.nkb = ct // L.kc + L.nbias = L.nbw if L.op != OP_HC else 4 + if L.res and L.nbw != L.n: + raise ValueError(f"{L.name}: residual layers need one n-block (nbw {L.nbw}, n {L.n})") + + +def stage_bytes(L: Layer) -> int: + """L1 staging (CB_RES memory) of a layer's whole-page DRAM writes: UP one output a-row of every (r, kx) of the + unit, RA one 32-pixel output page, C3 with several n-blocks per core the unit's whole pixels, HC per tile column + two 16 x 32 fp32 output half tiles (face pairs)""" + if L.op == OP_UP: + k = L.s + return L.bh * L.bw * k * 32 * (L.n * 32 // (k * k)) * 2 + if L.op == OP_RA: + return 32 * L.n * 64 + if L.op == OP_HC: + return L.bw * 4096 + if L.nbi > 1: + return L.bh * L.bw * 32 * L.n * 64 + return 0 + + +def pair_mode(L: Layer) -> bool: + """C3 / HC with one channel tile per k-block out of a wider row and an even number of k-blocks: the kernel + tilizes channel tiles (kb, kb + 1) together and keeps them for both k-blocks (no wasted half of a 2-tile chunk)""" + if os.environ.get("DEPTHPRO2_MK_DEC_PAIR", "0") != "1": # implemented, not yet validated on the device + return False + return L.op in (OP_C3, OP_HC) and L.kc == 1 and L.nkb % 2 == 0 and L.s * (L.cin // 32) > 1 + + +def block_tiles(L: Layer) -> Tuple[int, int]: + """tiles of one k-block (without / with the k-block 0 bias tiles)""" + if L.op == OP_C3: + t = 9 * L.kc * L.nbw + elif L.op == OP_HC: + t = 16 * L.kc + else: + t = L.kc * L.nbw + return t, t + L.nbias + + +def assign_pages(layers: Sequence[Layer]) -> int: + """weight-arena page offsets: per layer, per n-block nb, per k-block kb a page-padded block""" + page = 0 + for L in layers: + t, t0 = block_tiles(L) + L.bp, L.bp0 = cdiv(t, PAGE_TILES), cdiv(t0, PAGE_TILES) + L.wpg = page + page += (L.n // L.nbw) * (L.bp0 + (L.nkb - 1) * L.bp) + return page + + +def block_page(L: Layer, nb: int, kb: int) -> int: + """first arena page of block (nb, kb) of layer L""" + return L.wpg + nb * (L.bp0 + (L.nkb - 1) * L.bp) + (0 if kb == 0 else L.bp0 + (kb - 1) * L.bp) diff --git a/code/tt_depthpro2/tt/mk_dec/program.py b/code/tt_depthpro2/tt/mk_dec/program.py new file mode 100644 index 0000000000000000000000000000000000000000..1f216b9350c46caad78db4c89e893345cb084e3a --- /dev/null +++ b/code/tt_depthpro2/tt/mk_dec/program.py @@ -0,0 +1,366 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The DEC megakernel: ONE persistent ``ttnn.generic_op`` program per (size, T, Hp, Wp) that runs DepthPro2's whole +decoder stage (reassemble + DPT fusion decoder + head) for all T frames and writes the float32 inverse depth. + +``MkDecWeights(device, host_weights, size)`` builds the weight arena (every layer's tile stream, plan.static_cfg) and +the constants once per size; ``MkDec(device, weights, shape)`` plans the shape (plan.Plan), allocates the persistent +DRAM maps (zero-initialized: their pads / guard rows are never written), the HC selector tiles and the plan table; +``run(taps)`` only enqueues the program (no host sync, trace-capturable) and returns ``inv`` ``[T, Hp, Wp]`` float32 +TILE DRAM (a new tensor per call: ``tt/model.py`` deallocates the warm-up output). + +Contract (SPEC section 3): taps ``[1, 1, T * Np, C]`` bf16 TILE DRAM (frame t's patch rows t * Np .. t * Np + N - 1 +in raster order, rows >= N ignored). +""" + +from __future__ import annotations + +import os +import time +from typing import Dict, List, Optional, Sequence, Tuple + +import torch + +from . import plan as P +from . import wprep as WP + +# DEPTHPRO2_MK_DEC_KDIR: development copy of the kernel directory (same md_defs.hpp layout); default kernels/ +_KDIR = os.environ.get("DEPTHPRO2_MK_DEC_KDIR", P.KDIR) +KERNELS = {r: os.path.join(_KDIR, f"md_{r}.cpp") for r in ("ncrisc", "brisc", "trisc")} + + +def _opt_level(name: str): + from ttnn._ttnn.operations.experimental.fabric_mux import KernelBuildOptLevel + + return getattr(KernelBuildOptLevel, name) + + +def env_options() -> Dict: + """``DEPTHPRO2_MK_DEC_OPTS`` (comma-separated ``key=value``): ``fid`` (HiFi4 / HiFi3 / HiFi2).""" + out: Dict = {} + for kv in os.environ.get("DEPTHPRO2_MK_DEC_OPTS", "").split(","): + if "=" not in kv: + continue + k, v = (t.strip() for t in kv.split("=", 1)) + if k == "fid": + out["fidelity"] = v + else: + raise ValueError(f"DEPTHPRO2_MK_DEC_OPTS: unknown key {k!r}") + return out + + +def _ref_layers(size: str, gx: int, gy: int) -> List[P.Layer]: + """the layer list of a size (shape-independent stream parameters; any bucket gives the same list)""" + return P.Plan(size, 1, 64, 64, gx, gy).layers + + +class MkDecWeights: + """The weight arena (bf16 ROW_MAJOR pages of 8 tiles) and constants of one size, shared by every shape.""" + + def __init__(self, device, host_weights: Dict[str, torch.Tensor], size: str, timings: Optional[Dict] = None): + import ttnn + + t0 = time.perf_counter() + g = device.compute_with_storage_grid_size() + self.size, self.grid = size, (int(g.x), int(g.y)) + layers = _ref_layers(size, *self.grid) + arena = WP.build_arena(layers, host_weights) + consts = WP.const_tiles(host_weights) + t1 = time.perf_counter() + dram = ttnn.DRAM_MEMORY_CONFIG + self.arena = ttnn.from_torch(arena.reshape(1, 1, *arena.shape).contiguous(), dtype=ttnn.bfloat16, + layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram) + self.consts = ttnn.from_torch(consts.reshape(-1, 32).contiguous(), dtype=ttnn.bfloat16, + layout=ttnn.TILE_LAYOUT, device=device, memory_config=dram) + self.pages = arena.shape[0] + self.dram_bytes = arena.numel() * 2 + self.layer_sig = [(L.name, L.kc, L.nbw, L.wpg) for L in layers] + if timings is not None: + timings["mk_dec_fold_s"] = t1 - t0 + timings["mk_dec_upload_s"] = time.perf_counter() - t1 + + +class MkDec: + def __init__(self, device, weights: MkDecWeights, size: str, T: int, hp: int, wp: int, fidelity: str = "HiFi4", + opt: str = "O2", dm_opt: str = "Os", group: Optional[int] = None, + defines: Sequence[Tuple[str, str]] = ()): + import ttnn + + self.device = device + g = device.compute_with_storage_grid_size() + self.grid = (int(g.x), int(g.y)) + env = env_options() + fidelity = env.pop("fidelity", fidelity) + if (weights.size, weights.grid) != (size, self.grid): + raise ValueError(f"prepared weights {weights.size}/{weights.grid} do not match {size}/{self.grid}") + self.weights = weights + self.plan = pl = P.Plan(size, T, hp, wp, *self.grid, group=group) + if [(L.name, L.kc, L.nbw, L.wpg) for L in pl.layers] != weights.layer_sig: + raise RuntimeError("weight-arena layout differs from the shape's plan (static_cfg must not depend on shape)") + self.T, self.hp, self.wp = T, hp, wp + self.fidelity, self.opt, self.dm_opt = fidelity, opt, dm_opt + self.extra_defines = list(defines) + self._noc: Dict[Tuple[int, int], Tuple[int, int]] = {} + for x in range(self.grid[0]): + for y in range(self.grid[1]): + c = device.worker_core_from_logical_core(ttnn.CoreCoord(x, y)) + self._noc[(x, y)] = (int(c.x), int(c.y)) + for x in range(self.grid[0] - 1): # logical order must be NoC order (rectangles map corner to corner) + if self._noc[(x, 0)][0] >= self._noc[(x + 1, 0)][0]: + raise RuntimeError("logical x order differs from NoC x order") + for y in range(self.grid[1] - 1): + if self._noc[(0, y)][1] >= self._noc[(0, y + 1)][1]: + raise RuntimeError("logical y order differs from NoC y order") + dram = ttnn.DRAM_MEMORY_CONFIG + self.maps = [] + for m in pl.maps: + self.maps.append(ttnn.zeros([1, 1, m.pages, 32 * m.C], dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, + device=device, memory_config=dram)) + sel = WP.sel_tiles(hp, wp) + self.sel = ttnn.from_torch(sel.reshape(-1, 32).contiguous(), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, + device=device, memory_config=dram) + table = pl.table() + self.plan_words = len(table) + pad = max(-len(table) % 8, P.MIN_REQ // 4 - len(table)) # one >= 2 KB DRAM read + tw = torch.tensor(table + [0] * pad, dtype=torch.int64).to(torch.int32).reshape(1, -1) + self.plan_t = ttnn.from_torch(tw, dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, device=device, + memory_config=dram) + self.plan_bytes = tw.shape[1] * 4 + nc = self.grid[0] * self.grid[1] + # one 2 KB page per core (every DRAM write of the program is >= 2 KB); the first DBG_WORDS words are used + self.dbg = ttnn.from_torch(torch.zeros(1, 1, nc, P.DBG_PAGE, dtype=torch.int32), dtype=ttnn.uint32, + layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram) + self.spin = int(os.environ.get("DEPTHPRO2_MK_DEC_SPIN", str(1 << 26))) + self.prof_t = ttnn.from_torch(torch.zeros(1, 1, nc, P.PROF_WORDS, dtype=torch.int32), dtype=ttnn.uint32, + layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram) + self._acc = list(ttnn.TensorAccessorArgs(self.weights.arena).get_compile_time_args()) + self._desc: Dict[Tuple, object] = {} + self.cb = self._cb_sizes() + + # ------------------------------------------------------------------ L1 + def _cb_sizes(self) -> Dict[str, int]: + sz = self.plan.cb_sizes() + band = -(-sz["band"] // P.T16) * P.T16 + # a second band page lets the BRISC read unit k + 1's band while the TRISC computes unit k + rest = sum(v for k, v in sz.items() if k != "band") + P.T16 + 4096 + pages = 2 if (os.environ.get("DEPTHPRO2_MK_DEC_PIPE", "0") == "1" + and rest + 2 * band <= int(os.environ.get("DEPTHPRO2_MK_DEC_L1_KB", "1380")) * 1024) else 1 + self.band_pages = pages + return dict(w=sz["w"], band=band, band_total=pages * band, tapa_cap=pages * band // P.T16, + a_cap=sz["a"] // P.T16 + 1, res=sz["res"], + acc_cap=sz["acc"] // P.T32, sel_cap=sz["sel"] // P.T16, plan=-(-self.plan_bytes // 16) * 16) + + def cb_table(self): + cb = self.cb + T16, T32 = P.T16, P.T32 + return [ + (((P.CB_W, "bf16", T16, False),), cb["w"]), + (((P.CB_BAND, "raw", cb["band"], False), (P.CB_TAPA, "bf16", T16, False)), cb["band_total"]), + (((P.CB_A, "bf16", T16, False),), cb["a_cap"] * T16), + (((P.CB_RES, "raw", cb["res"], False),), cb["res"]), + (((P.CB_ACC, "fp32", T32, True),), cb["acc_cap"] * T32), + (((P.CB_OUT, "bf16", T16, False),), P.OUT_CAP * T16), + (((P.CB_CONST, "bf16", T16, False),), P.N_CONST * T16), + (((P.CB_SEL, "bf16", T16, False),), cb["sel_cap"] * T16), + (((P.CB_Z, "bf16", T16, False),), 16 * T16), + (((P.CB_HO, "fp32", T32, False),), 2 * T32), + (((P.CB_SYNC, "raw", P.SYNC_BYTES, False),), P.SYNC_BYTES), + (((P.CB_PLAN, "raw", cb["plan"], False),), cb["plan"]), + ] + + def l1_bytes(self) -> int: + return sum(n for _, n in self.cb_table()) + + # ------------------------------------------------------------------ args + def noc(self, xy) -> Tuple[int, int]: + return self._noc[tuple(xy)] + + def persistent(self) -> List: + return [self.weights.arena, self.weights.consts, self.sel, self.plan_t, self.dbg, self.prof_t, *self.maps] + + def common_args(self, taps, out, nl: int) -> List[int]: + gx, gy = self.grid + c = [0] * (P.N_COMMON_FIXED + len(self.maps)) + x0, y0 = self.noc((0, 0)) + x1, y1 = self.noc((gx - 1, gy - 1)) + c[P.K_ALL_X0], c[P.K_ALL_Y0], c[P.K_ALL_X1], c[P.K_ALL_Y1] = x0, y0, x1, y1 + c[P.K_N_ALL] = gx * gy + c[P.K_HUB_X], c[P.K_HUB_Y] = self.noc((0, 0)) + c[P.K_NL] = int(nl) + c[P.K_WTS] = self.weights.arena.buffer_address() + c[P.K_CONST] = self.weights.consts.buffer_address() + c[P.K_SEL] = self.sel.buffer_address() + c[P.K_OUT] = out.buffer_address() + for i in range(4): + c[P.K_TAP0 + i] = taps[i].buffer_address() + c[P.K_PLANA] = self.plan_t.buffer_address() + c[P.K_PLANB] = self.plan_bytes + c[P.K_DBG] = self.dbg.buffer_address() + c[P.K_SPIN] = self.spin + c[P.K_PROF] = self.prof_t.buffer_address() + for i, m in enumerate(self.maps): + c[P.K_MAP0 + i] = m.buffer_address() + return c + + def core_args(self) -> Dict[Tuple[int, int], List[int]]: + gx, gy = self.grid + out = {} + for y in range(gy): + for x in range(gx): + a = [0] * P.N_RT_ARGS + a[P.A_IDX] = y * gx + x + a[P.A_ROLE] = (P.R_FEED if x == 0 else 0) | (P.R_HUB if (x, y) == (0, 0) else 0) + a[P.A_X], a[P.A_Y] = x, y + a[P.A_ROWX0] = self.noc((min(1, gx - 1), y))[0] + a[P.A_ROWX1] = self.noc((gx - 1, y))[0] + a[P.A_ROWY] = self.noc((0, y))[1] + a[P.A_FX], a[P.A_FY] = self.noc((0, y)) + out[(x, y)] = a + return out + + def defines(self) -> List[Tuple[str, str]]: + gx, gy = self.grid + cb = self.cb + d = [("MD_GX", str(gx)), ("MD_GY", str(gy)), ("MD_A_CAP", str(cb["a_cap"])), ("MD_ACC_CAP", str(cb["acc_cap"])), + ("MD_TAPA_CAP", str(cb["tapa_cap"])), ("MD_SEL_CAP", str(cb["sel_cap"])), ("MD_OPT_" + self.opt, "1"), + ("MD_DMOPT_" + self.dm_opt, "1")] # the JIT disk cache key ignores opt_level + # opt-in experiments (DEPTHPRO2_MK_DEC_PIPE=1: BRISC unit pipelining; _FEED_DEPTH: feeder DRAM reads in flight) + if os.environ.get("DEPTHPRO2_MK_DEC_PIPE", "0") == "1": + d.append(("MD_PIPE", "1")) + ms = os.environ.get("DEPTHPRO2_MK_DEC_MCAST_SAFE", "0") + if ms in ("1", "2"): # 1: unlinked + acked before the flag, 2: unlinked, ordered by the static VC + d.append(("MD_MCAST_SAFE", ms)) + if os.environ.get("DEPTHPRO2_MK_DEC_FEED_SERIAL", "0") == "1": + d.append(("MD_FEED_SERIAL", "1")) + if os.environ.get("DEPTHPRO2_MK_DEC_FEED_DEPTH"): + d.append(("MD_FEED_DEPTH", str(int(os.environ["DEPTHPRO2_MK_DEC_FEED_DEPTH"])))) + fid = {"LoFi": 0, "HiFi2": 2, "HiFi3": 3, "HiFi4": 4}[self.fidelity] + if fid != 4: + d.append(("MD_FID", str(fid))) + return d + self.extra_defines + + def program(self, taps, out, nl: Optional[int] = None): + import ttnn + + nl = len(self.plan.layers) if nl is None else int(nl) + common = self.common_args(taps, out, nl) + key = tuple(common) + if key in self._desc: + return self._desc[key] + gx, gy = self.grid + cores = ttnn.CoreRangeSet([ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(gx - 1, gy - 1))]) + fmt = {"bf16": ttnn.bfloat16, "fp32": ttnn.float32, "raw": ttnn.bfloat16} + cbs = [] + modes = [ttnn.UnpackToDestMode.Default] * 64 + for ids, total in self.cb_table(): + fds = [] + for cb_id, f, page, unpack32 in ids: + fds.append(ttnn.CBFormatDescriptor(buffer_index=cb_id, data_format=fmt[f], page_size=page)) + if unpack32: + modes[cb_id] = ttnn.UnpackToDestMode.UnpackToDestFp32 + cbs.append(ttnn.CBDescriptor(total_size=total, core_ranges=cores, format_descriptors=fds)) + ct = list(self._acc) + args = self.core_args() + rt = ttnn.RuntimeArgs() + for x in range(gx): + for y in range(gy): + rt[x][y] = args[(x, y)] + cc = ttnn.ComputeConfigDescriptor(math_fidelity=getattr(ttnn.MathFidelity, self.fidelity), + fp32_dest_acc_en=True, dst_full_sync_en=False, math_approx_mode=False) + cc.unpack_to_dest_mode = modes + defines = self.defines() + fp = ttnn.KernelDescriptor.SourceType.FILE_PATH + dm = ttnn.DataMovementConfigDescriptor + kernels = [ + ttnn.KernelDescriptor(kernel_source=KERNELS["ncrisc"], source_type=fp, core_ranges=cores, + compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines, + config=dm(processor=ttnn.DataMovementProcessor.RISCV_1, noc=ttnn.NOC.NOC_0), + opt_level=_opt_level(self.dm_opt)), + ttnn.KernelDescriptor(kernel_source=KERNELS["brisc"], source_type=fp, core_ranges=cores, + compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines, + config=dm(processor=ttnn.DataMovementProcessor.RISCV_0, noc=ttnn.NOC.NOC_1), + opt_level=_opt_level(self.dm_opt)), + ttnn.KernelDescriptor(kernel_source=KERNELS["trisc"], source_type=fp, core_ranges=cores, + compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines, + config=cc, opt_level=_opt_level(self.opt)), + ] + sems = [ttnn.SemaphoreDescriptor(id=i, core_ranges=cores, initial_value=0) for i in (0, 1)] + desc = ttnn.ProgramDescriptor(kernels=kernels, semaphores=sems, cbs=cbs) + self._desc[key] = desc + return desc + + def alloc_out(self): + import ttnn + + return ttnn.allocate_tensor_on_device(ttnn.Shape([self.T, self.hp, self.wp]), ttnn.float32, ttnn.TILE_LAYOUT, + self.device, ttnn.DRAM_MEMORY_CONFIG) + + def run(self, taps, out=None, nl: Optional[int] = None): + """Enqueue the DEC program (one ``generic_op``) and return the inverse depth ``[T, Hp, Wp]`` float32 TILE + (``out`` given: written in place). ``nl`` < number of layers (debug): run only the first ``nl`` layers (the + maps they produce are readable with :meth:`read_map`).""" + import ttnn + + taps = list(taps) + if out is None: + out = self.alloc_out() + io = [*self.persistent(), *taps, out] + ttnn.generic_op(io, self.program(taps, out, nl)) + return out + + # ------------------------------------------------------------------ debug readers + def read_map(self, name: str, f: int = 0) -> torch.Tensor: + """map ``name`` of group frame f as ``[C, H, W]`` float32 (interior pixels)""" + import ttnn + + g = next(m for m in self.plan.maps if m.name == name) + st = ttnn.to_torch(self.maps[g.idx]).float().reshape(g.frames, g.fpix, g.C)[f] + img = torch.stack([st[g.g(y, 0):g.g(y, 0) + g.W] for y in range(g.H)]) + return img.permute(2, 0, 1) + + def read_dbg(self) -> torch.Tensor: + """per-core abort diagnostics [NC, DBG_WORDS] (all zero = no bounded wait gave up)""" + import ttnn + + return ttnn.to_torch(self.dbg).reshape(-1, P.DBG_PAGE)[:, :P.DBG_WORDS].to(torch.int64) & 0xFFFFFFFF + + def read_prof(self) -> torch.Tensor: + """MD_PROF builds: [NC, PROF_WORDS] wall-clock ticks (md_defs.hpp PROF_WORDS layout)""" + import ttnn + + return ttnn.to_torch(self.prof_t).reshape(-1, P.PROF_WORDS).to(torch.int64) & 0xFFFFFFFF + + def aborts(self) -> List[Tuple[int, List[int]]]: + d = self.read_dbg() + out = [] + for i in range(d.shape[0]): + w = d[i].tolist() + if w[0] or w[2] or w[4] or w[6] or w[11] or w[13]: + out.append((i, w[:10] + [w[11] | w[13]])) # [..., exit-barrier timeout bits] + return out + + def read_storage(self, name: str) -> torch.Tensor: + import ttnn + + g = next(m for m in self.plan.maps if m.name == name) + return ttnn.to_torch(self.maps[g.idx]).float().reshape(g.frames, g.fpix, g.C) + + +class Engine: + """SPEC section 3 stage-engine adapter (``tt/__init__.py`` contract): ``Engine(device, weights, shape)`` with + ``weights`` = :meth:`prepare_weights` (shared by every shape) or the host dict (+ ``size``); ``run(taps)`` -> + ``inv`` ``[T, Hp, Wp]`` float32 TILE DRAM (a new tensor per call).""" + + def __init__(self, device, weights, shape, size: Optional[str] = None, **kw): + if isinstance(weights, dict): + if size is None: + raise ValueError("size is required with host weights") + weights = MkDecWeights(device, weights, size) + self.shape = shape + self.mk = MkDec(device, weights, weights.size, shape.frames, shape.hp, shape.wp, **kw) + + @staticmethod + def prepare_weights(device, host_weights, size: str) -> MkDecWeights: + return MkDecWeights(device, host_weights, size) + + def run(self, taps): + return self.mk.run(taps) diff --git a/code/tt_depthpro2/tt/mk_dec/wprep.py b/code/tt_depthpro2/tt/mk_dec/wprep.py new file mode 100644 index 0000000000000000000000000000000000000000..540663755b74ab27d2caeac173d718f2ddc72d01 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_dec/wprep.py @@ -0,0 +1,217 @@ +# SPDX-License-Identifier: Apache-2.0 +"""DEC megakernel host weight preparation: per layer dense fp32 operands (folds in fp32, one bf16 rounding per +weight), the weight arena (every layer's tile stream, page-padded blocks, in the TRISC's consumption order; +``plan.static_cfg``), the constant tiles and the HC bias selector tiles. + +Folds: + +* fusion deconv (k2s2, no bias) followed by the 1x1 out_conv: one per-pixel matmul ``[d, 4d]`` (N = (a, b, co)), + bias = out_conv bias; +* head.1 (convT k2s2, d/2 -> d/2, bias b1) o head.2 (3x3, d/2 -> 32, bias b2): a 3x3 conv on the half-resolution + map with 4 sub-pixel outputs (a, b); sub-pixel (a, b) uses the half-res neighbours (oy, ox) with + oy in {a - 1, a}, ox in {b - 1, b}; the bias of an output pixel depends on which neighbours exist (head.1's bias + only enters through taps inside the image): 9 pixel classes (top / middle / bottom x left / middle / right), + selected per pixel by a selector matmul; +* biases are bf16 hi + lo (fp32-accurate) tiles consumed through a ones operand (constant E01). +""" + +from __future__ import annotations + +from typing import Dict, List, Tuple + +import torch + +from . import plan as P + +TILE = 32 + + +def tilize(blocks: torch.Tensor) -> torch.Tensor: + """``[N, 32, 32]`` -> ``[N, 1024]`` in tile order (4 faces of 16 x 16, each row-major).""" + n = blocks.shape[0] + return blocks.reshape(n, 2, 16, 2, 16).permute(0, 1, 3, 2, 4).reshape(n, 1024) + + +def untilize(flat: torch.Tensor) -> torch.Tensor: + n = flat.shape[0] + return flat.reshape(n, 2, 2, 16, 16).permute(0, 1, 3, 2, 4).reshape(n, 32, 32) + + +def hi_lo(v: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + hi = v.float().to(torch.bfloat16).float() + return hi, (v.float() - hi).to(torch.bfloat16).float() + + +def bias_tile(v: torch.Tensor) -> torch.Tensor: + t = torch.zeros(32, 32) + t[0], t[1] = hi_lo(v) + return t + + +def _pad(t: torch.Tensor, shape) -> torch.Tensor: + out = torch.zeros(shape) + out[tuple(slice(0, s) for s in t.shape)] = t + return out + + +# ----------------------------------------------------------------------------------------------- per-layer operands + + +def hc_operands(w: Dict[str, torch.Tensor], cin_p: int): + """head.1 o head.2 composite: Wc [4 sub, 4 neighbour, cin_p, 32], bias per (class, sub) [9, 4, 32].""" + w1, b1 = w["head.1.weight"].double(), w["head.1.bias"].double() # [d/2, d/2, 2, 2] (in, out), [d/2] + w2, b2 = w["head.2.weight"].double(), w["head.2.bias"].double() # [32, d/2, 3, 3], [32] + ci = w1.shape[0] + wc = torch.zeros(4, 4, cin_p, 32, dtype=torch.float64) + bias = torch.zeros(9, 4, 32, dtype=torch.float64) + for a in range(2): + for b in range(2): + sub = 2 * a + b + for dy in (-1, 0, 1): + for dx in (-1, 0, 1): + oy, ap = (a + dy) // 2, (a + dy) % 2 + ox, bp = (b + dx) // 2, (b + dx) % 2 + o = (oy - (a - 1)) * 2 + (ox - (b - 1)) + w2t = w2[:, :, dy + 1, dx + 1] # [32, d/2] + wc[sub, o, :ci] += w1[:, :, ap, bp] @ w2t.t() # [ci, 32] + bt = w2t @ b1 # [32] + for ycls in range(3): + if (ycls == 0 and oy < 0) or (ycls == 2 and oy > 0): + continue + for xcls in range(3): + if (xcls == 0 and ox < 0) or (xcls == 2 and ox > 0): + continue + bias[ycls * 3 + xcls, sub] += bt + bias[:, sub] += b2 + return wc.float(), bias.float() + + +def layer_operands(L: P.Layer, w: Dict[str, torch.Tensor], cin_raw: int, cout_raw: int): + """dense fp32 operands of a layer: (W, bias) with W shaped per op (see module doc), bias [N * 32] or (HC) + [9, 4, 32].""" + ct = L.cin // 32 + cin_p = L.cin + if L.op == P.OP_HC: + return hc_operands(w, cin_p) + if L.op == P.OP_C3: + wt = w[L.wkey + ".weight"] # [co, ci, 3, 3] + cout_p = L.n * 32 + W = torch.zeros(9, cin_p, cout_p) + for t in range(9): + W[t, :wt.shape[1], :wt.shape[0]] = wt[:, :, t // 3, t % 3].t() + b = w.get(L.wkey + ".bias") + bias = torch.zeros(cout_p) + if b is not None: + bias[:b.numel()] = b + return W, bias + if L.op == P.OP_RA: + wt = w[L.wkey + ".weight"].reshape(w[L.wkey + ".weight"].shape[0], -1) # [co, ci] + cout_p = L.n * 32 + W = torch.zeros(cin_p, cout_p) + W[:wt.shape[1], :wt.shape[0]] = wt.t() + bias = torch.zeros(cout_p) + bias[:wt.shape[0]] = w[L.wkey + ".bias"] + return W, bias + # UP + k = L.s + cout_p = L.n * 32 // (k * k) + if L.wkey.endswith(".up"): # fused fusion deconv + out_conv + p = L.wkey[:-3] + wd = w[p + ".deconv.weight"].double() # [ci, co, 2, 2] + wo = w[p + ".out_conv.weight"].double()[:, :, 0, 0] # [co2, co] + wt = torch.einsum("ioab,po->ipab", wd, wo).float() + b = w[p + ".out_conv.bias"] + else: + wt = w[L.wkey + ".weight"] # [ci, co, k, k] + b = w[L.wkey + ".bias"] + W = torch.zeros(cin_p, k, k, cout_p) + W[:wt.shape[0], :, :, :wt.shape[1]] = wt.permute(0, 2, 3, 1) + bias = torch.zeros(k, k, cout_p) + bias[:, :, :b.numel()] = b + return W.reshape(cin_p, -1), bias.reshape(-1) + + +def block_tile_list(L: P.Layer, W, bias, nb: int, kb: int) -> List[torch.Tensor]: + """the 32 x 32 fp32 tiles of block (nb, kb) in the TRISC's consumption order (plan.static_cfg)""" + out: List[torch.Tensor] = [] + nbw = L.nbw + if kb == 0: + if L.op == P.OP_HC: + for sub in range(4): + t = torch.zeros(32, 32) + for cls in range(9): + t[2 * cls], t[2 * cls + 1] = hi_lo(bias[cls, sub]) + out.append(t) + else: + for n in range(nbw): + c0 = (nb * nbw + n) * 32 + out.append(bias_tile(bias[c0:c0 + 32])) + for c in range(L.kc): + ci = (kb * L.kc + c) * 32 + if L.op == P.OP_C3: + for t in range(9): + for n in range(nbw): + c0 = (nb * nbw + n) * 32 + out.append(W[t, ci:ci + 32, c0:c0 + 32]) + elif L.op == P.OP_HC: + for sub in range(4): + for o in range(4): + out.append(W[sub, o, ci:ci + 32, :]) + else: + for n in range(nbw): + c0 = (nb * nbw + n) * 32 + out.append(W[ci:ci + 32, c0:c0 + 32]) + return out + + +def build_arena(layers: List[P.Layer], w: Dict[str, torch.Tensor], cin_raw=None) -> torch.Tensor: + """bf16 ``[pages, PAGE_TILES * 1024]``: every layer's blocks at ``plan.block_page``""" + total = P.assign_pages(layers) + arena = torch.zeros(total, P.PAGE_TILES, 1024, dtype=torch.bfloat16) + for L in layers: + W, bias = layer_operands(L, w, 0, 0) + for nb in range(L.n // L.nbw): + for kb in range(L.nkb): + tiles = block_tile_list(L, W, bias, nb, kb) + pg = P.block_page(L, nb, kb) + flat = tilize(torch.stack(tiles)).to(torch.bfloat16) + npg = P.cdiv(len(tiles), P.PAGE_TILES) + buf = torch.zeros(npg * P.PAGE_TILES, 1024, dtype=torch.bfloat16) + buf[:len(tiles)] = flat + arena[pg:pg + npg] = buf.reshape(npg, P.PAGE_TILES, 1024) + return arena.reshape(total, P.PAGE_TILES * 1024) + + +def const_tiles(w: Dict[str, torch.Tensor]) -> torch.Tensor: + """bf16 constants [N_CONST, 32, 32] (fp32 values exactly representable in bf16)""" + c = torch.zeros(P.N_CONST, 32, 32) + c[P.C_E01, :, 0:2] = 1.0 + c[P.C_I] = torch.eye(32) + w4 = w["head.4.weight"].reshape(-1).float() + hi, lo = hi_lo(w4) + for s in range(4): + c[P.C_W4H + s, s] = hi + c[P.C_W4L + s, s] = lo + c[P.C_E4, 0:4, 0:2] = 1.0 + b4 = w["head.4.bias"].reshape(-1)[0].float() + bh, bl = hi_lo(b4.reshape(1)) + c[P.C_B4T, :, 0] = bh # in1 of a transposed matmul: (E4 @ C_B4T^T)[s, p] = hi + lo for s < 4 + c[P.C_B4T, :, 1] = bl + return c + + +def sel_tiles(hp: int, wp: int) -> torch.Tensor: + """HC bias selector tiles [3 * KX, 32, 32]: (row class ycls, x tile kx) -> row r has ones in columns 2 cls and + 2 cls + 1 (cls = 3 ycls + xcls of pixel x = 32 kx + r).""" + h2, w2 = hp // 2, wp // 2 + kx = P.cdiv(w2, 32) + out = torch.zeros(3 * kx, 32, 32) + for ycls in range(3): + for k in range(kx): + for r in range(32): + x = 32 * k + r + xcls = 0 if x == 0 else (2 if x == w2 - 1 else 1) + cls = 3 * ycls + xcls + out[ycls * kx + k, r, 2 * cls] = 1.0 + out[ycls * kx + k, r, 2 * cls + 1] = 1.0 + return out diff --git a/code/tt_depthpro2/tt/mk_enc/__init__.py b/code/tt_depthpro2/tt/mk_enc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2ec03cf9c982cd441ac709702cfeb8d5f0745d81 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_enc/__init__.py @@ -0,0 +1,6 @@ +# SPDX-License-Identifier: Apache-2.0 +"""DepthPro2 ENC megakernel (one persistent generic_op for the whole encoder / the FOV trunk). + +``Engine`` is the stage-engine entry point ``tt/model.py`` loads for ``enc=mk`` (``tt.mk_enc.Engine``).""" + +from .program import Engine, MkEnc, MkEncWeights # noqa: F401 diff --git a/code/tt_depthpro2/tt/mk_enc/arena.py b/code/tt_depthpro2/tt/mk_enc/arena.py new file mode 100644 index 0000000000000000000000000000000000000000..a02858e87708d7766839baa37154af2d52d4c964 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_enc/arena.py @@ -0,0 +1,264 @@ +# SPDX-License-Identifier: Apache-2.0 +"""ENC megakernel host side: weight folds, the per-column weight streams (each grid column's tiles in the TRISC's +consumption order, bf16, pages of 8 tiles), the constant tiles and the host patchify. + +Folds (fp32, each weight rounded once to bf16): + +* LayerNorm into the consumer (QKV <- norm1, FC1 <- norm2): ``LN(x) W + b = rstd (x W' - mu c) + bias'`` with + ``W' = diag(gamma) W``, ``c = colsum(bf16(W'))``, ``bias' = beta W + b``; the extra K tile ``X`` has row 0 = ``c`` + and row 1 = ``bias'`` (in0 = ``EXT = [-mu | std]``). +* attention scale 1/8 into the q columns (exact power of two); +* LayerScale ``gamma_1`` / ``gamma_2`` into the proj / fc2 output columns and their biases; +* bias-only ops (embed, proj, fc2): extra K tile row 0 = the bias (in0 = ``E0``, ones in column 0). +""" + +from __future__ import annotations + +import math +from typing import Dict, List, Optional, Tuple + +import torch + +from . import geometry as G + +TILE = 32 +HEAD_DIM = 64 +ATT_SCALE = HEAD_DIM ** -0.5 # 1/8: exact +ROPE_TEMPERATURE = 100.0 + + +def tilize(blocks: torch.Tensor) -> torch.Tensor: + """``[N, 32, 32]`` -> ``[N, 1024]`` in tile order (4 faces of 16 x 16, each row-major).""" + n = blocks.shape[0] + return blocks.reshape(n, 2, 16, 2, 16).permute(0, 1, 3, 2, 4).reshape(n, 1024) + + +def tile_grid(wt: torch.Tensor) -> torch.Tensor: + """``W^T [K, N]`` -> ``[Kt, Nt, 32, 32]`` tiles.""" + k, n = wt.shape + return wt.reshape(k // TILE, TILE, n // TILE, TILE).permute(0, 2, 1, 3) + + +def _hilo(v: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + """``v`` = hi + lo with hi = bf16(v), lo = bf16(v - hi) (relative error ~2^-17).""" + v = v.float() + hi = v.to(torch.bfloat16).float() + return hi, (v - hi).to(torch.bfloat16).float() + + +def _ext(row0: torch.Tensor, row1: Optional[torch.Tensor] = None) -> torch.Tensor: + """The extra K tiles ``[Nt, 32, 32]`` (bf16), every value carried as a hi / lo pair so that the bias and the LN-fold + correction stay fp32-accurate (a bf16 bias / column sum was a systematic per-channel error: B img_375x500_pad tap3 + error -30 %, MK_LOG round 6). + + * bias-only ops (in0 = E0, 1 in columns 0 and 1): rows 0, 1 = hi, lo of ``row0``; + * LN-folded ops (in0 = EXT = [-mu hi, -mu lo, std hi, std lo, -mu hi, std hi], me_trisc stats_in): + rows 0, 1 = hi(c), rows 2, 3 = hi(bias'), row 4 = lo(c), row 5 = lo(bias').""" + n = row0.numel() + e = torch.zeros(TILE, n) + h0, l0 = _hilo(row0) + if row1 is None: + e[0], e[1] = h0, l0 + else: + h1, l1 = _hilo(row1) + e[0] = e[1] = h0 + e[2] = e[3] = h1 + e[4], e[5] = l0, l1 + return e.reshape(TILE, n // TILE, TILE).permute(1, 0, 2) + + +def _ln_fold(wt: torch.Tensor, b: Optional[torch.Tensor], g: torch.Tensor, beta: torch.Tensor, + col_scale: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]: + """``(W' tiles bf16 [Kt, Nt, 32, 32], X tiles [Nt, 32, 32])`` of an LN-folded op.""" + wt, g, beta = wt.float(), g.float(), beta.float() + wf = g[:, None] * wt + bias = beta @ wt + (b.float() if b is not None else 0.0) + if col_scale is not None: + wf = wf * col_scale[None] + bias = bias * col_scale + wb = wf.to(torch.bfloat16) + return tile_grid(wb), _ext(wb.float().sum(0), bias) + + +def _bias_op(wt: torch.Tensor, b: torch.Tensor, col_scale: Optional[torch.Tensor] = None + ) -> Tuple[torch.Tensor, torch.Tensor]: + wt, b = wt.float(), b.float() + if col_scale is not None: + wt = wt * col_scale[None] + b = b * col_scale + return tile_grid(wt.to(torch.bfloat16)), _ext(b) + + +def fold(w: Dict[str, torch.Tensor], geo: G.Geometry, prefix: str) -> Dict: + """Folded tile grids of the encoder (or the FOV trunk) from the safetensors dict ``w``.""" + f = lambda n: w[prefix + n].float() # noqa: E731 + d = geo.dim + pw = f("patch_embed.proj.weight").reshape(d, -1) # [D, 768] in (c, ky, kx) order + out: Dict = {"embed": _bias_op(pw.t(), f("patch_embed.proj.bias"))} + pfx = torch.zeros(TILE, d) + pfx[0] = f("cls_token").reshape(d) + pfx[1:5] = f("reg_token").reshape(4, d) + out["pfx"] = pfx + qscale = torch.ones(3 * d) + qscale[:d] = ATT_SCALE + blocks = [] + for i in range(geo.L): + p = f"blocks.{i}." + blk = {"qkv": _ln_fold(f(p + "attn.qkv.weight").t(), w.get(prefix + p + "attn.qkv.bias"), + f(p + "norm1.weight"), f(p + "norm1.bias"), qscale)} + g1, g2 = f(p + "gamma_1"), f(p + "gamma_2") + blk["proj"] = _bias_op(f(p + "attn.proj.weight").t(), f(p + "attn.proj.bias"), g1) + n2w, n2b = f(p + "norm2.weight"), f(p + "norm2.bias") + if geo.swiglu: + blk["fc1g"] = _ln_fold(f(p + "mlp.fc1_g.weight").t(), f(p + "mlp.fc1_g.bias"), n2w, n2b) + blk["fc1u"] = _ln_fold(f(p + "mlp.fc1_x.weight").t(), f(p + "mlp.fc1_x.bias"), n2w, n2b) + else: + blk["fc1"] = _ln_fold(f(p + "mlp.fc1.weight").t(), f(p + "mlp.fc1.bias"), n2w, n2b) + blk["fc2"] = _bias_op(f(p + "mlp.fc2.weight").t(), f(p + "mlp.fc2.bias"), g2) + blocks.append(blk) + out["blocks"] = blocks + return out + + +# ------------------------------------------------------------------------------------------------ column streams +def _grouped(op: Tuple[torch.Tensor, torch.Tensor], n0: int, nx: int, gw: int) -> List[torch.Tensor]: + """Residual ops (embed / proj / fc2): power-of-two n-groups <= ``gw`` tiles, largest first: [k-major tiles, then + the extra tile per j]; the op segment is padded to whole pages.""" + tg, ex = op + parts = [] + g0 = 0 + for nj in G.pow2_groups(nx, gw): + cols = slice(n0 + g0, n0 + g0 + nj) + parts.append(tg[:, cols].reshape(-1, TILE, TILE)) + parts.append(ex[cols].to(torch.bfloat16)) + g0 += nj + return _page_pad(parts) + + +def _page_pad(parts: List[torch.Tensor]) -> List[torch.Tensor]: + n = sum(p.reshape(-1, TILE, TILE).shape[0] for p in parts) + pad = G.pad8(n) - n + return parts + ([torch.zeros(pad, TILE, TILE, dtype=torch.bfloat16)] if pad else []) + + +def _qkv(op, h0: int, nh: int) -> List[torch.Tensor]: + tg, ex = op + parts = [] + for u in range(h0, h0 + nh): + cols = slice(2 * u, 2 * u + 2) + parts.append(tg[:, cols].reshape(-1, TILE, TILE)) + parts.append(ex[cols].to(torch.bfloat16)) + return _page_pad(parts) + + +def _fc1(blk: Dict, f0: int, nf: int, fb: int, swiglu: bool) -> List[torch.Tensor]: + parts = [] + b0 = 0 + for nb in G.pow2_groups(nf, fb): + cols = slice(f0 + b0, f0 + b0 + nb) + if swiglu: + (tg_g, ex_g), (tg_u, ex_u) = blk["fc1g"], blk["fc1u"] + w = torch.stack([tg_g[:, cols], tg_u[:, cols]], 2) # [Kt, nb, 2, 32, 32]: gate, up per hidden tile + e = torch.stack([ex_g[cols], ex_u[cols]], 1) + parts.append(w.reshape(-1, TILE, TILE)) + parts.append(e.reshape(-1, TILE, TILE).to(torch.bfloat16)) + else: + tg, ex = blk["fc1"] + parts.append(tg[:, cols].reshape(-1, TILE, TILE)) + parts.append(ex[cols].to(torch.bfloat16)) + b0 += nb + return _page_pad(parts) + + +def _pad_pages(parts: List[torch.Tensor], tiles: int) -> torch.Tensor: + x = torch.cat([p.reshape(-1, TILE, TILE).to(torch.bfloat16) for p in parts]) + assert x.shape[0] == tiles, (x.shape, tiles) + pad = -(-tiles // G.PAGE_TILES) * G.PAGE_TILES - tiles + if pad: + x = torch.cat([x, torch.zeros(pad, TILE, TILE, dtype=x.dtype)]) + return x + + +def arena(fw: Dict, geo: G.Geometry, kind: str, l: int = 0) -> torch.Tensor: + """Phase arena ``kind`` ("E": embed + QKV(0); "B": proj / fc1 / fc2 of block l + QKV(l + 1); "BL": the last + block, no QKV): the columns' streams back to back, ``[pages, 8 * 1024]`` bf16 in tile order.""" + cols = [] + for x in range(geo.C): + parts: List[torch.Tensor] = [] + if kind == "E": + parts += _grouped(fw["embed"], geo.n0[x], geo.nx[x], geo.G) + parts += _qkv(fw["blocks"][0]["qkv"], geo.h0[x], geo.nh[x]) + else: + blk = fw["blocks"][l] + parts += _grouped(blk["proj"], geo.n0[x], geo.nx[x], geo.G) + parts += _fc1(blk, geo.f0[x], geo.nf[x], geo.FBW, geo.swiglu) + parts += _grouped(blk["fc2"], geo.n0[x], geo.nx[x], geo.G) + if kind == "B": + parts += _qkv(fw["blocks"][l + 1]["qkv"], geo.h0[x], geo.nh[x]) + t = _pad_pages(parts, geo.arena_tiles(kind, x)) + assert t.shape[0] == geo.arena_pages(kind, x) * G.PAGE_TILES + cols.append(t) + a = torch.cat(cols) + return tilize(a).reshape(-1, G.PAGE_TILES * 1024) + + +# ------------------------------------------------------------------------------------------------ constants +def const_tiles() -> torch.Tensor: + """bf16 constants ``[N_CONST, 32, 32]`` (me_defs.hpp C_*).""" + c = torch.zeros(G.N_CONST, TILE, TILE) + c[G.C_ONES] = 1.0 + c[G.C_E0, :, 0:2] = 1.0 # bias hi + lo rows of the X tile + for q in range(2 * G.RB_MAX): + c[G.C_L0 + q, :, q] = 1.0 + c[G.C_SEL0 + q, q, :] = 1.0 + for s in range(G.RB_MAX): + c[G.C_PA, 2 * s, s] = 1.0 + c[G.C_PA, 8 + 2 * s, s] = 1.0 + c[G.C_PB, 2 * s + 1, s] = 1.0 + c[G.C_PB, 8 + 2 * s + 1, s] = 1.0 + c[G.C_PM0 + s, s, 0] = c[G.C_PM0 + s, s, 4] = -1.0 # EXT col 0 / 4: -mu hi (times c hi / c lo) + c[G.C_PM1 + s, s, 1] = -1.0 # EXT col 1: -mu lo + c[G.C_PS0 + s, s, 2] = c[G.C_PS0 + s, s, 5] = 1.0 # EXT col 2 / 5: std hi (times bias' hi / lo) + c[G.C_PS1 + s, s, 3] = 1.0 # EXT col 3: std lo + c[G.C_I] = torch.eye(TILE) + for k in range(8): + c[G.C_SH8, k, k + 8] = 1.0 + return c + + +def cf32_tiles(nlast: int) -> torch.Tensor: + c = torch.zeros(G.N_CF32, TILE, TILE) + c[G.F_NEG0, :, 0] = -1.0 + c[G.F_ONE1, :, 1] = 1.0 + c[G.F_MASKP, :, G.NUM_PREFIX:] = -1e9 + c[G.F_MASKN, :, nlast:] = -1e9 + return c + + +def rope_tiles(gh: int, gw: int, pt: int) -> torch.Tensor: + """fp32 ``[Pt * 32, 64]``: columns 0..31 = cos, 32..63 = sin (one RoPE half; DINOv3 rope_table, rotate-half).""" + 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) + angles = (2 * math.pi * coords[:, :, None] / periods[None, None, :]).flatten(1) # [N, 32] + out = torch.zeros(pt * TILE, 2 * TILE) + out[:angles.shape[0], :TILE] = angles.cos() + out[:angles.shape[0], TILE:] = angles.sin() + return out + + +def patchify(x: torch.Tensor) -> torch.Tensor: + """Padded frames ``(T, 3, Hp, Wp)`` -> ``patches [T * Np, 768]`` (row ``t * Np + n``, raster order, (c, ky, kx) + columns = ``patch_embed.proj.weight.reshape(D, 768)``; rows >= N of a frame are zero).""" + t, c, h, w = x.shape + gh, gw = h // 16, w // 16 + n = gh * gw + np_ = -(-n // 32) * 32 + p = x.reshape(t, c, gh, 16, gw, 16).permute(0, 2, 4, 1, 3, 5).reshape(t, n, c * 256) + out = torch.zeros(t, np_, c * 256, dtype=x.dtype) + out[:, :n] = p + return out.reshape(t * np_, c * 256) diff --git a/code/tt_depthpro2/tt/mk_enc/geometry.py b/code/tt_depthpro2/tt/mk_enc/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..f4a0a6d45493b70e071c98168a99adf7d28ebc78 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_enc/geometry.py @@ -0,0 +1,405 @@ +# SPDX-License-Identifier: Apache-2.0 +"""ENC megakernel geometry (host mirror of ``kernels/me_defs.hpp`` + the ``ME_*`` kernel defines): row tiles, waves, +per-column N splits, attention items, the CB table (L1 budget) and the runtime args, for one program +(size, T, gh, gw, mode) on a ``gx x gy`` grid (``device.compute_with_storage_grid_size()``, never hard-coded). + +Row tiles (``ri``, 32 tokens each): ``ri < T`` prefix tile of frame ``ri``; ``T <= ri < T + T*Pt`` patch tile +``(t, p)`` (``ri = T + t*Pt + p``); ``ri = Mt - 1`` the pool tile (T > 1 with joint blocks). Wave ``w``, grid row +``y``, slot ``s`` -> ``ri = (w*RB + s)*R + y``. +""" + +from __future__ import annotations + +import math +import os +import re +from dataclasses import dataclass, field +from typing import Callable, Dict, List, Optional, Tuple + +KDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels") +DEFS_PATH = os.path.join(KDIR, "me_defs.hpp") + + +def _parse_defs(path: str = DEFS_PATH) -> Dict[str, int]: + out = {} + pat = re.compile(r"^\s*constexpr\s+uint32_t\s+([A-Z0-9_]+)\s*=\s*([0-9]+)\s*;") + with open(path) as f: + for line in f: + m = pat.match(line) + if m: + out[m.group(1)] = int(m.group(2)) + return out + + +D = _parse_defs() +globals().update(D) + +Core = Tuple[int, int] +T16, T32 = 2048, 4096 +PAGE_TILES = 8 +PE_T = 24 # patch K tiles (768 = 3 * 16 * 16) +NUM_PREFIX = 5 +L1_BUDGET = 1400 * 1024 # allocatable CB bytes we allow ourselves (default worker_l1_size ~1427 KB) + +#: model sizes (reference/model.py SIZES; FOV trunk = ViT-S) +SIZE_CFG = { + "S": dict(dim=384, depth=12, heads=6, hidden=1536, swiglu=False, taps=(2, 5, 8, 11), cross=(5, 7, 9, 11)), + "B": dict(dim=768, depth=12, heads=12, hidden=3072, swiglu=False, taps=(2, 5, 8, 11), cross=(5, 7, 9, 11)), + "L": dict(dim=1024, depth=24, heads=16, hidden=4096, swiglu=False, taps=(5, 11, 17, 23), + cross=(9, 11, 13, 15, 17, 19, 21, 23)), + "H": dict(dim=1280, depth=32, heads=20, hidden=5120, swiglu=True, taps=(7, 15, 23, 31), + cross=(11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31)), +} +#: default slots per row and wave (L1 budget, MK_LOG 1.3) +RB_DEFAULT = {"S": 4, "B": 2, "L": 2, "H": 2} +#: blocks whose attention logits reach |s| > 1e3 on the goldens (S blk 0: 2.2e6, B 0: 2.1e5, L 1: 1.2e4, H 0 / 1: +#: 1.9e4 / 1.1e4, FOV trunk 0: 2.6e6; every other block < 700): they use the two-step (fp32-accurate) row max +GIANT = {"S": (0,), "B": (0,), "L": (1,), "H": (0, 1), "fov": (0,)} + + +def pow2_groups(n: int, gmax: int) -> List[int]: + """n split into power-of-two groups <= gmax, largest first (keeps every group's per-k tiles inside one 8-tile + weight page when each op segment starts page-aligned; mirrored in me_trisc.cpp pow2_floor)""" + out = [] + while n > 0: + g = 1 + while g * 2 <= min(gmax, n): + g *= 2 + out.append(g) + n -= g + return out + + +def pad8(t: int) -> int: + return -(-t // PAGE_TILES) * PAGE_TILES + + +def split(total: int, parts: int) -> List[int]: + return [total // parts + (1 if i < total % parts else 0) for i in range(parts)] + + +def starts(sizes: List[int]) -> List[int]: + out, a = [], 0 + for s in sizes: + out.append(a) + a += s + return out + + +@dataclass +class Geometry: + size: str + T: int + gh: int + gw: int + mode: str # "depth" | "fov" + gx: int + gy: int + rb: int = 0 + qb: int = 0 + kc: int = 32 + ring: int = 10 + probe: bool = False + prof: bool = False + exp_mode: int = 1 # P = exp(S - m): 0 fp32-accurate exp, 1 exp_21f (bf16-accurate, max rel err 1.7e-3) + gelu_mode: int = 1 # 0 exact erf GELU (SFPU), 1 polynomial (max |err| 2.1e-4, MoGe-2 v5) + giant_all: bool = False # two-step row max in every block + alias_st: bool = True # the attention state FIFO (fp32) is a view of CB_INX's memory (bf16 LN gather) + fc1p_ok: bool = True # allow the pipelined FC1 epilogue (rb == 2, GELU) + derived: Dict = field(default_factory=dict) + + def __post_init__(self): + if self.size not in SIZE_CFG: + raise ValueError(f"size {self.size!r}") + if self.mode not in ("depth", "fov"): + raise ValueError(f"mode {self.mode!r}") + if self.mode == "fov" and self.size != "S": + raise ValueError("the FOV trunk is ViT-S") + c = SIZE_CFG[self.size] + self.dim, self.L, self.H = c["dim"], c["depth"], c["heads"] + self.DT, self.FT = self.dim // 32, c["hidden"] // 32 + self.swiglu = bool(c["swiglu"]) + self.taps = tuple(c["taps"]) + self.freeze = tuple(c["cross"]) + self.joint = tuple(c["cross"]) if self.mode == "depth" else () + if not 1 <= self.T <= 32: + raise ValueError(f"T={self.T}") + self.N = self.gh * self.gw + self.Np = -(-self.N // 32) * 32 + self.Pt = self.Np // 32 + self.nlast = self.N - (self.Pt - 1) * 32 + self.pool = 1 if (self.T > 1 and self.joint) else 0 + self.Mt = self.T + self.T * self.Pt + self.pool + self.C, self.R = self.gx, self.gy + self.NC = self.gx * self.gy + if self.rb == 0: + self.rb = RB_DEFAULT[self.size] + if self.rb not in (1, 2, 4): + raise ValueError(f"rb={self.rb}") + self.W = -(-self.Mt // (self.R * self.rb)) + # column splits (each op on its own, contiguous) + nh = split(3 * self.H, self.C) + nx = split(self.DT, self.C) + nf = split(self.FT, self.C) + if min(nh) < 1 or min(nx) < 1 or min(nf) < 1: + raise ValueError("more grid columns than op tiles") + self.nh, self.h0 = nh, starts(nh) + self.nx, self.n0 = nx, starts(nx) + self.nf, self.f0 = nf, starts(nf) + self.NXM, self.NHM, self.NFM = max(nx), max(nh), max(nf) + # DST groups + self.G = 8 // self.rb # proj / fc2 / embed n-group width (accumulators rb * G <= 8) + # FC1 f-block width: accumulators rb * FB (SwiGLU: 2 rb * FB) <= 4, rstd of the slots at DST 4 + s + self.FB = (2 // self.rb) if self.swiglu else (4 // self.rb) + # pipelined FC1 (GELU on the pack thread, half-sync DST): rb == 2 GELU sizes (B, L); weights per f tile + self.fc1p = (not self.swiglu) and self.rb == 2 and self.fc1p_ok + self.FBW = 1 if self.fc1p else self.FB + if self.FB < 1: + raise ValueError("SwiGLU needs rb <= 4") + # attention + self.q_per_head = self._q_tiles_per_head() + if self.qb == 0: + self.qb = self._best_qb() + if self.kc not in (8, 16, 32): + raise ValueError(f"kc={self.kc}: 8, 16 or 32 (the score region = kc tiles = also the 8-tile RAW CB)") + # no longer chunks than a within-frame segment needs (1 + Pt key tiles) + while self.kc > 8 and self.kc // 2 >= self.Pt + 1: + self.kc //= 2 + self._check_budget() + + # -------------------------------------------------------------- rows + def ri_of(self, w: int, y: int, s: int) -> int: + return (w * self.rb + s) * self.R + y + + def slot_of(self, ri: int) -> Tuple[int, int, int]: + q, y = divmod(ri, self.R) + w, s = divmod(q, self.rb) + return w, y, s + + def kind(self, ri: int) -> str: + if ri < self.T: + return "prefix" + if ri < self.T + self.T * self.Pt: + return "patch" + if self.pool and ri == self.Mt - 1: + return "pool" + return "empty" + + @property + def pool_slot(self) -> Optional[Tuple[int, int, int]]: + return self.slot_of(self.Mt - 1) if self.pool else None + + def _best_qb(self) -> int: + """q tiles per core and attention job: minimizes rounds x qb (the per-core critical path) over the blocks, + preferring larger qb (fewer K / V reads) on ties""" + best, cost = 1, None + for qb in range(1, 9): + c = 0 + for joint, nq in ((False, self.Pt + 1), (True, self.T * self.Pt)): + if joint and not self.joint: + continue + pairs = self.H if joint else self.H * self.T + jobs = pairs * -(-nq // (self.R * qb)) + c += -(-jobs // self.C) * qb * ((self.T * self.Pt + 1) if joint else (self.Pt + 1)) + if cost is None or c <= cost: + best, cost = qb, c + return best + + def _q_tiles_per_head(self) -> int: + """query tiles per head in a within-frame block (the larger case)""" + return self.T * (self.Pt + 1) + + # -------------------------------------------------------------- weights per column (tiles, consumption order) + # every op segment is padded to whole pages (8 tiles): the block matmuls need each k row of a group in one page + def tiles_embed(self, x: int) -> int: + return pad8(self.nx[x] * (PE_T + 1)) + + def tiles_qkv(self, x: int) -> int: + return pad8(self.nh[x] * 2 * (self.DT + 1)) + + def tiles_proj(self, x: int) -> int: + return pad8(self.nx[x] * (self.DT + 1)) + + def tiles_fc1(self, x: int) -> int: + return pad8(self.nf[x] * (2 if self.swiglu else 1) * (self.DT + 1)) + + def tiles_fc2(self, x: int) -> int: + return pad8(self.nx[x] * (self.FT + 1)) + + def pages(self, tiles: int) -> int: + return -(-tiles // PAGE_TILES) + + def arena_tiles(self, kind: str, x: int) -> int: + if kind == "E": + return self.tiles_embed(x) + self.tiles_qkv(x) + t = self.tiles_proj(x) + self.tiles_fc1(x) + self.tiles_fc2(x) + return t + (self.tiles_qkv(x) if kind == "B" else 0) + + def arena_pages(self, kind: str, x: int) -> int: + return self.pages(self.arena_tiles(kind, x)) + + def page0(self, kind: str, x: int) -> int: + return sum(self.arena_pages(kind, i) for i in range(x)) + + def pages_total(self, kind: str) -> int: + return sum(self.arena_pages(kind, i) for i in range(self.C)) + + # -------------------------------------------------------------- CB table (bytes per core) + def cb_table(self) -> List[Tuple[Tuple[Tuple[int, str, bool], ...], int]]: + """[(((cb id, fmt, unpack-to-dest fp32), ...), total bytes)]; ids in one entry share the allocation (the + attention-phase CBs KV / ST / AP are views of the wave-phase INF / INX / RAW memory; MK_LOG 1.7).""" + rb, nxm = self.rb, self.NXM + b = lambda i, n: (((i, "bf16", False),), n * T16) # noqa: E731 + f = lambda i, n, u: (((i, "fp32", u),), n * T32) # noqa: E731 + return [ + b(CB_W, self.ring * PAGE_TILES), + ] + ([(((CB_INX, "bf16", False), (CB_ST, "fp32", True)), self.inx_bytes)] if self.alias_st else [ + (((CB_INX, "bf16", False),), self.rb * self.DT * T16), + f(CB_ST, (self.qb + 1) * 4, True), + ]) + [ + (((CB_INF, "bf16", False), (CB_KV, "bf16", False)), self.inf_tiles * T16), + f(CB_STAT, self.C, False), + f(CB_X, 2 * rb * nxm, True), + f(CB_SUMS, 4 * rb, False), + f(CB_STO, 1, False), + b(CB_OUTX, nxm * rb), + b(CB_EXT, rb), + f(CB_RSTD, rb, True), + (((CB_RAW, "fp32", True), (CB_S32, "fp32", True), (CB_S32F, "fp32", False), (CB_AP, "fp32", False)), + max(8, self.kc) * T32), + b(CB_OUT, 2 * 2 * rb), # double-buffered: the TRISC packs unit u + 1 while the BRISC writes unit u + b(CB_FO, 2 * self.FB * rb), # double-buffered + b(CB_CONST, N_CONST), + f(CB_CF32, N_CF32, True), + f(CB_TAB, 2 * rb, True), + f(CB_XO, nxm, True), + b(CB_TAP, nxm), + ] + ([f(CB_PL, nxm, True)] if self.pool else []) + [ + f(CB_PFX, nxm, True), + f(CB_XL, rb * nxm, True), + b(CB_AQ, 2 * self.qb * 2), + f(CB_MX, 1, False), + f(CB_MFN, 3, True), + f(CB_MF1, 1, True), + b(CB_SC, 6), # mu / rstd / std hi + lo: every value is a bf16 (hi = bf16(v), lo = bf16(v - hi)) + b(CB_AO, self.qb * 2), + (((CB_SYNC, "raw", False),), SYNC_BYTES), + b(CB_TOK, 1), + ] + ([f(CB_PRB, N_PROBE, False)] if self.probe else []) + + @property + def inf_tiles(self) -> int: + """CB_INF tiles (the wave gathers' capacity), rounded up to whole K / V chunks (4 KC tiles)""" + return -(-self.inf_cap // (4 * self.kc)) * (4 * self.kc) + + @property + def inf_cap(self) -> int: + return self.rb * max(self.FT, self.DT, PE_T) + + @property + def inx_bytes(self) -> int: + """CB_INX bytes: the LN gather (rb * DT bf16) or the attention state FIFO ((qb + 1) * 4 fp32 tiles), whole + 16 KB states""" + need = max(self.rb * self.DT * T16, (self.qb + 1) * 4 * T32) + return -(-need // (4 * T32)) * (4 * T32) + + def cb_bytes(self) -> int: + return sum(n for _, n in self.cb_table()) + + def _check_budget(self): + """shrink, in order: the K / V chunk (32 -> 16 key tiles), the weight ring (10 -> 6 pages), the chunk again + (16 -> 8), then the q tiles per attention job""" + steps = 0 + while self.cb_bytes() > L1_BUDGET: + if self.kc > 16: + self.kc //= 2 + elif self.ring > 6: + self.ring -= 2 + elif self.kc > 8 and self.qb <= 2: + self.kc //= 2 + elif self.qb > 1: + self.qb -= 1 + else: + raise ValueError(f"CBs need {self.cb_bytes() // 1024} KB > {L1_BUDGET // 1024} KB (size {self.size}, " + f"rb {self.rb})") + steps += 1 + + # -------------------------------------------------------------- attention items + def n_items(self, l: int) -> int: + """attention jobs of block l""" + nq = self.T * self.Pt if l in self.joint else self.Pt + (0 if l in self.freeze else 1) + pairs = self.H if l in self.joint else self.H * self.T + return pairs * -(-nq // (self.R * self.qb)) + + # -------------------------------------------------------------- defines + def defines(self) -> List[Tuple[str, str]]: + jm = sum(1 << l for l in self.joint) + gm = sum(1 << l for l in range(self.L)) if self.giant_all else sum( + 1 << l for l in GIANT["fov" if self.mode == "fov" else self.size]) + fm = sum(1 << l for l in self.freeze) + d = { + "ME_DT": self.DT, "ME_FT": self.FT, "ME_H": self.H, "ME_L": self.L, "ME_SWIGLU": int(self.swiglu), + "ME_C": self.C, "ME_R": self.R, "ME_RB": self.rb, "ME_T": self.T, "ME_PT": self.Pt, + "ME_NLAST": self.nlast, "ME_W": self.W, "ME_POOL": self.pool, "ME_MT": self.Mt, "ME_QB": self.qb, + "ME_KC": self.kc, "ME_JOINT": f"{jm}u", "ME_GIANT": f"{gm}u", "ME_EXP": self.exp_mode, "ME_GELU": self.gelu_mode, "ME_FREEZE": f"{fm}u", "ME_FOV": int(self.mode == "fov"), + "ME_TAP0": self.taps[0], "ME_TAP1": self.taps[1], "ME_TAP2": self.taps[2], "ME_TAP3": self.taps[3], + "ME_NXM": self.NXM, "ME_NHM": self.NHM, "ME_NFM": self.NFM, "ME_G": self.G, "ME_FB": self.FB, "ME_FC1P": int(self.fc1p), + "ME_PROBE": int(self.probe), "ME_PROF": int(self.prof), "ME_RING": self.ring, "ME_NC": self.NC, "ME_INF": self.inf_cap, "ME_INFT": self.inf_tiles, + "ME_INXT": (self.inx_bytes if self.alias_st else self.rb * self.DT * T16) // T16, + "ME_ABI_HOST": ME_ABI, # noqa: F821 (parsed from me_defs.hpp) + } + return [(k, str(v)) for k, v in d.items()] + + # -------------------------------------------------------------- runtime args + def core_args(self, noc: Callable[[Core], Core]) -> Dict[Core, List[int]]: + out = {} + ks = split(self.DT, self.C) + ks0 = starts(ks) + pk = split(PE_T, self.C) + pk0 = starts(pk) + hub = (self.gx - 1, self.gy - 1) + for y in range(self.gy): + for x in range(self.gx): + a = [0] * N_RT_ARGS + role = 0 + if y == 0: + role |= R_FEED + if y == self.gy - 1: + role |= R_KVR + if (x, y) == hub: + role |= R_HUB + a[A_IDX], a[A_ROLE], a[A_X], a[A_Y] = y * self.gx + x, role, x, y + a[A_H0], a[A_NH] = self.h0[x], self.nh[x] + a[A_N0], a[A_NX] = self.n0[x], self.nx[x] + a[A_F0], a[A_NF] = self.f0[x], self.nf[x] + a[A_KS0], a[A_KS1] = ks0[x], ks0[x] + ks[x] + a[A_PK0], a[A_PK1] = pk0[x], pk0[x] + pk[x] + a[A_ROWX0] = noc((0, y))[0] + a[A_ROWX1] = noc((self.gx - 1, y))[0] + a[A_ROWY] = noc((x, y))[1] + a[A_FX], a[A_FY] = noc((x, 0)) + a[A_COLY0] = noc((x, 1))[1] + a[A_COLY1] = noc((x, self.gy - 1))[1] + py = self.pool_slot[1] if self.pool else 0 + a[A_POOLX], a[A_POOLY] = noc((x, py)) + a[A_P0E], a[A_NPE] = self.page0("E", x), self.arena_pages("E", x) + a[A_P0B], a[A_NPB] = self.page0("B", x), self.arena_pages("B", x) + a[A_P0BL], a[A_NPBL] = self.page0("BL", x), self.arena_pages("BL", x) + a[A_KRX], a[A_KRY] = noc((x, self.gy - 1)) + a[A_KY0] = noc((x, 0))[1] + a[A_KY1] = noc((x, self.gy - 2))[1] + out[(x, y)] = a + return out + + def hub(self) -> Core: + return (self.gx - 1, self.gy - 1) + + def rect(self, noc: Callable[[Core], Core]) -> List[int]: + x0, y0 = noc((0, 0)) + x1, y1 = noc((self.gx - 1, self.gy - 1)) + return [min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1)] + + def summary(self) -> str: + return (f"{self.size} {self.mode} T={self.T} grid {self.gh}x{self.gw} (N={self.N}, Pt={self.Pt}, " + f"nlast={self.nlast}) Mt={self.Mt} W={self.W} rb={self.rb} qb={self.qb} kc={self.kc} " + f"ring={self.ring} CB={self.cb_bytes() // 1024} KB") diff --git a/code/tt_depthpro2/tt/mk_enc/kernels/me_brisc.cpp b/code/tt_depthpro2/tt/mk_enc/kernels/me_brisc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6eeafcdad44cad040712a5b82433a9c97ba6f591 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_enc/kernels/me_brisc.cpp @@ -0,0 +1,549 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// DepthPro2 ENC megakernel, BRISC (NoC 1): the boot barrier, the global hub barriers, every DRAM read of the op +// inputs (constants, rope tables, patches, x, q / K / V, attention output), every DRAM write (q / k / v staging, the +// attention output, taps, x), and the row gathers: +// IA patches / attention output: each core reads its share of the K tiles of the row's slots from DRAM and +// multicasts it to the row (-> CB_INF, k * RB + s) +// IX LN input: the packed partial statistics (-> slot x of CB_STAT) and bf16(x) (-> CB_INX, k * RB + s) +// IF FC1 output blocks (-> CB_INF, f * RB + s) +// Every gather is a loopback multicast of the slice plus one flag word set to a per-type generation; the landing CB is +// pushed at full capacity once every flag of the round reached it. WAR safety of the landing buffers follows from the +// dataflow (MK_LOG 1.3): a core sends round g + 1 of a buffer only after it received data that every row core sends +// after its last read of round g. +#include "me_dm.hpp" + +using namespace mex; + +namespace { + +constexpr auto acc_dram = TensorAccessorArgs(); +#define ME_NOINL __attribute__((noinline)) + +struct Me { + uint32_t idx, role, x, y, h0, nh, n0, nx, f0, nf, ks0, ks1, pk0, pk1, rowx0, rowx1, rowy, poolx, pooly; + uint32_t ax0, ay0, ax1, ay1, nall, hubx, huby, nl, dump; + uint32_t kd[RB], ri[RB]; +}; +Me me; +uint32_t gen_ix = 0, gen_ia = 0, gen_if = 0, gen_bar = 0, gen_pool = 0, gen_fd = 0; + +FORCE_INLINE void dbg(uint32_t a, uint32_t b) { + *sync_ptr(W_DBG) = a; + *sync_ptr(W_DBG + 1) = b; +} +ME_NOINL void wait_ge(uint32_t w, uint32_t v) { + WAYPOINT("BWGE"); + *sync_ptr(W_DBG + 2) = w; + *sync_ptr(W_DBG + 3) = v; + while (sync_read(w) < v) { + } +} +ME_NOINL void wait_all(uint32_t w0, uint32_t n, uint32_t v) { + for (uint32_t i = 0; i < n; ++i) { + wait_ge(w0 + i, v); + } +} +FORCE_INLINE void land(uint32_t cb, uint32_t cap) { + cb_reserve_back(cb, cap); + cb_push_back(cb, cap); +} + +FORCE_INLINE auto dram(uint32_t addr, uint32_t page_bytes) { return TensorAccessor(acc_dram, addr, page_bytes); } +ME_NOINL void rd16(uint32_t addr, uint32_t page, uint32_t l1) { noc_async_read_page(page, dram(addr, T16), l1); } +ME_NOINL void rd32(uint32_t addr, uint32_t page, uint32_t l1) { noc_async_read_page(page, dram(addr, T32), l1); } +ME_NOINL void wr16(uint32_t addr, uint32_t page, uint32_t l1) { noc_async_write_page(page, dram(addr, T16), l1); } +ME_NOINL void wr32(uint32_t addr, uint32_t page, uint32_t l1) { noc_async_write_page(page, dram(addr, T32), l1); } + +// multicast [src, src + bytes) to the same-offset address dst on every core of my grid row (loopback) +ME_NOINL void row_data(uint32_t src, uint32_t dst, uint32_t bytes, bool linked) { + noc_async_write_multicast_loopback_src(src, mcast_addr(me.rowx0, me.rowy, me.rowx1, me.rowy, dst), bytes, C, + linked); +} +ME_NOINL void row_flag(uint32_t flag_word, uint32_t src_word, uint32_t v) { + const uint32_t srcw = sync_addr(W_SRC + src_word); + *reinterpret_cast(srcw) = v; + noc_semaphore_set_multicast_loopback_src( + srcw, mcast_addr(me.rowx0, me.rowy, me.rowx1, me.rowy, sync_addr(flag_word)), C); + noc_async_writes_flushed(); +} + +void load_args() { + me.idx = rt(A_IDX); + me.role = rt(A_ROLE); + me.x = rt(A_X); + me.y = rt(A_Y); + me.h0 = rt(A_H0); + me.nh = rt(A_NH); + me.n0 = rt(A_N0); + me.nx = rt(A_NX); + me.f0 = rt(A_F0); + me.nf = rt(A_NF); + me.ks0 = rt(A_KS0); + me.ks1 = rt(A_KS1); + me.pk0 = rt(A_PK0); + me.pk1 = rt(A_PK1); + me.rowx0 = rt(A_ROWX0); + me.rowx1 = rt(A_ROWX1); + me.rowy = rt(A_ROWY); + me.poolx = rt(A_POOLX); + me.pooly = rt(A_POOLY); + me.ax0 = ca(K_ALL_X0); + me.ay0 = ca(K_ALL_Y0); + me.ax1 = ca(K_ALL_X1); + me.ay1 = ca(K_ALL_Y1); + me.nall = ca(K_N_ALL); + me.hubx = ca(K_HUB_X); + me.huby = ca(K_HUB_Y); + me.nl = ca(K_NL); + me.dump = ca(K_DUMP); +} + +void kinds(uint32_t w) { + for (uint32_t s = 0; s < RB; ++s) { + me.ri[s] = ri_of(w, me.y, s); + me.kd[s] = kind_of(me.ri[s]); + } +} + +void boot_barrier() { + const uint32_t sem_boot = get_semaphore(0); + const uint32_t sem_go = get_semaphore(1); + noc_semaphore_inc(get_noc_addr(me.hubx, me.huby, sem_boot), 1); + noc_async_atomic_barrier(); + if (me.role & R_HUB) { + volatile tt_l1_ptr uint32_t* b = reinterpret_cast(sem_boot); + WAYPOINT("BOOT"); + while (true) { + invalidate_l1_cache(); + if (*b >= me.nall) { + break; + } + } + volatile tt_l1_ptr uint32_t* go = reinterpret_cast(sem_go); + *go = 1; + noc_semaphore_set_multicast_loopback_src(sem_go, mcast_addr(me.ax0, me.ay0, me.ax1, me.ay1, sem_go), me.nall); + noc_async_writes_flushed(); + } + wait_go(sem_go); +} + +// global barrier: every write of this core landed, then the hub counts arrivals and multicasts the generation +ME_NOINL void barrier() { + ++gen_bar; + noc_async_write_barrier(); + noc_semaphore_inc(get_noc_addr(me.hubx, me.huby, sync_addr(W_BCNT)), 1); + noc_async_atomic_barrier(); + if (me.role & R_HUB) { + wait_ge(W_BCNT, gen_bar * me.nall); + const uint32_t srcw = sync_addr(W_SRC + SRC_BAR); + *reinterpret_cast(srcw) = gen_bar; + noc_semaphore_set_multicast_loopback_src(srcw, mcast_addr(me.ax0, me.ay0, me.ax1, me.ay1, sync_addr(W_BAR)), + me.nall); + noc_async_writes_flushed(); + } + wait_ge(W_BAR, gen_bar); +} + +// ------------------------------------------------------------------ init +void init_consts() { + cb_reserve_back(CB_CONST, N_CONST); + for (uint32_t i = 0; i < N_CONST; ++i) { + rd16(ca(K_CONST), i, get_write_ptr(CB_CONST) + i * T16); + } + cb_reserve_back(CB_CF32, N_CF32); + for (uint32_t i = 0; i < N_CF32; ++i) { + rd32(ca(K_CF32), i, get_write_ptr(CB_CF32) + i * T32); + } + cb_reserve_back(CB_PFX, NXM); + for (uint32_t j = 0; j < me.nx; ++j) { + rd32(ca(K_PFX), me.n0 + j, get_write_ptr(CB_PFX) + j * T32); + } + noc_async_read_barrier(); + if constexpr (POOL) { // valid frames n / bits(1 / n) of this run (VF tile elements 0, 1), for the TRISC too + cb_reserve_back(CB_PL, NXM); + const uint32_t a = get_write_ptr(CB_PL); + rd32(ca(K_VF), 0, a); + noc_async_read_barrier(); + invalidate_l1_cache(); + volatile tt_l1_ptr uint32_t* v = reinterpret_cast(a); + uint32_t n = v[0]; + n = n < 1 ? 1 : (n > T ? T : n); + g_nv = n; + *sync_ptr(W_NV) = n; + *sync_ptr(W_INVN) = v[1]; + } + cb_push_back(CB_CONST, N_CONST); // the TRISC reads W_NV / W_INVN after this push + cb_push_back(CB_CF32, N_CF32); + cb_push_back(CB_PFX, NXM); +} + +// ------------------------------------------------------------------ per wave +// rope tables of the wave's patch slots +void rope_tab() { + cb_reserve_back(CB_TAB, 2 * RB); + const uint32_t a = get_write_ptr(CB_TAB); + for (uint32_t s = 0; s < RB; ++s) { + if (me.kd[s] == KD_PATCH) { + const uint32_t p = (me.ri[s] - T) % PT; + rd32(ca(K_ROPE), 2 * p, a + (2 * s) * T32); + rd32(ca(K_ROPE), 2 * p + 1, a + (2 * s + 1) * T32); + } + } + noc_async_read_barrier(); + cb_push_back(CB_TAB, 2 * RB); +} + +// x of the wave from XD (NW > 1) +void x_load() { + cb_reserve_back(CB_XL, RB * NXM); + const uint32_t a = get_write_ptr(CB_XL); + for (uint32_t s = 0; s < RB; ++s) { + if (me.kd[s] == KD_PREFIX || me.kd[s] == KD_PATCH) { + for (uint32_t j = 0; j < me.nx; ++j) { + rd32(ca(K_XD), me.ri[s] * DT + me.n0 + j, a + (s * NXM + j) * T32); + } + } + } + noc_async_read_barrier(); + cb_push_back(CB_XL, RB * NXM); +} + +// IA: the row's slots' K tiles [k0, k1) of a DRAM tile tensor (Kt tiles per row tile) -> CB_INF (k * RB + s), my +// share read from DRAM and multicast to the row. mode 0: patches (row tile = patch index), 1: attention output. +ME_NOINL void ia_gather(uint32_t mode, uint32_t act) { + ++gen_ia; + const uint32_t k0 = mode == 0 ? me.pk0 : me.ks0, k1 = mode == 0 ? me.pk1 : me.ks1; + const uint32_t Kt = mode == 0 ? PE_T : DT; + const uint32_t addr = ca(mode == 0 ? K_PATCH : K_O); + const uint32_t base = cb_base(CB_INF); + for (uint32_t s = 0; s < RB; ++s) { + if (!(act & (1u << s))) { + continue; + } + const uint32_t row = mode == 0 ? me.ri[s] - T : me.ri[s]; + for (uint32_t k = k0; k < k1; ++k) { + rd16(addr, row * Kt + k, base + (k * RB + s) * T16); + } + } + noc_async_read_barrier(); + if (k1 > k0) { + row_data(base + k0 * RB * T16, base + k0 * RB * T16, (k1 - k0) * RB * T16, true); + } + row_flag(W_IA + me.x, SRC_IA, gen_ia); + wait_all(W_IA, C, gen_ia); + land(CB_INF, INF_CAP); +} + +// IX: packed statistics + bf16(x) slice +ME_NOINL void ln_gather() { + ++gen_ix; + cb_wait_front(CB_STO, 1); + cb_wait_front(CB_OUTX, NXM * RB); + row_data(get_read_ptr(CB_STO), cb_base(CB_STAT) + me.x * T32, T32, true); + row_data(get_read_ptr(CB_OUTX), cb_base(CB_INX) + me.n0 * RB * T16, me.nx * RB * T16, true); + row_flag(W_IX + me.x, SRC_IX, gen_ix); + cb_pop_front(CB_STO, 1); + cb_pop_front(CB_OUTX, NXM * RB); + wait_all(W_IX, C, gen_ix); + land(CB_STAT, C); + land(CB_INX, INX_CAP); +} + +// IF: FC1 output blocks (FB hidden tiles x RB slots each) +ME_NOINL void fc1_gather() { + ++gen_if; + const uint32_t base = cb_base(CB_INF); + for (uint32_t fb = 0; fb < me.nf;) { + uint32_t nb = 1; // the TRISC's power-of-two blocks (pow2_floor) + while (nb * 2 <= me.nf - fb && nb * 2 <= FB) { + nb *= 2; + } + cb_wait_front(CB_FO, FB * RB); + const uint32_t dst = base + (me.f0 + fb) * RB * T16; + row_data(get_read_ptr(CB_FO), dst, nb * RB * T16, false); + noc_async_writes_flushed(); + cb_pop_front(CB_FO, FB * RB); + fb += nb; + } + noc_async_write_barrier(); + row_flag(W_IF + me.x, SRC_IF, gen_if); + wait_all(W_IF, C, gen_if); + land(CB_INF, INF_CAP); +} + +ME_NOINL void store_x(uint32_t s) { + cb_wait_front(CB_XO, NXM); + const uint32_t a = get_read_ptr(CB_XO); + for (uint32_t j = 0; j < me.nx; ++j) { + wr32(ca(K_XD), me.ri[s] * DT + me.n0 + j, a + j * T32); + } + noc_async_writes_flushed(); + cb_pop_front(CB_XO, NXM); +} + +void tap_dm(uint32_t k) { + for (uint32_t s = 0; s < RB; ++s) { + if (!tap_on(me.kd[s])) { + continue; + } + cb_wait_front(CB_TAP, NXM); + const uint32_t a = get_read_ptr(CB_TAP), row = tap_row(me.ri[s]); + for (uint32_t j = 0; j < me.nx; ++j) { + wr16(ca(K_TAP0 + k), row * DT + me.n0 + j, a + j * T16); + } + noc_async_writes_flushed(); + cb_pop_front(CB_TAP, NXM); + } +} + +// before LN1 of a joint block: prefix slots -> XD + signal the pool owner; the pool owner reads the T slices +void pool_dm() { + bool own = false; + for (uint32_t s = 0; s < RB; ++s) { + if (me.kd[s] == KD_PREFIX) { + store_x(s); + noc_async_write_barrier(); + noc_semaphore_inc(get_noc_addr(me.poolx, me.pooly, sync_addr(W_POOL)), 1); + noc_async_atomic_barrier(); + } + own = own || me.kd[s] == KD_POOL; + } + if (!own) { + return; + } + ++gen_pool; + wait_ge(W_POOL, gen_pool * T); // every frame's prefix slots report; the mean takes frames < n + for (uint32_t t = 0; t < g_nv; ++t) { + cb_reserve_back(CB_PL, NXM); + const uint32_t a = get_write_ptr(CB_PL); + for (uint32_t j = 0; j < me.nx; ++j) { + rd32(ca(K_XD), t * DT + me.n0 + j, a + j * T32); + } + noc_async_read_barrier(); + cb_push_back(CB_PL, NXM); + } +} + +// q / k / v of block l: one OUT push (2 RB tiles) per head unit +void qkv_dm(uint32_t l) { + for (uint32_t jh = 0; jh < me.nh; ++jh) { + const uint32_t u = me.h0 + jh, ty = unit_type(u), h = unit_head(u); + const uint32_t addr = ca(ty == 0 ? K_Q : ty == 1 ? K_K : K_V); + cb_wait_front(CB_OUT, 2 * RB); + const uint32_t a = get_read_ptr(CB_OUT); + for (uint32_t s = 0; s < RB; ++s) { + if ((qkv_mask(l, me.kd[s]) >> ty) & 1u) { + wr16(addr, me.ri[s] * DT + 2 * h, a + (2 * s) * T16); + wr16(addr, me.ri[s] * DT + 2 * h + 1, a + (2 * s + 1) * T16); + } + } + noc_async_writes_flushed(); + cb_pop_front(CB_OUT, 2 * RB); + } +} + +void tail_dm(int l) { + const uint32_t l1 = (uint32_t)(l + 1); + if (l1 >= NL) { // QKV(l + 1) runs even past a debug stop (nl < L): the staging then holds block nl's q / k / v + return; + } + if (POOL && joint(l1)) { + pool_dm(); + } + ln_gather(); + qkv_dm(l1); +} + +void wave_end_dm(bool store) { + if (store) { + for (uint32_t s = 0; s < RB; ++s) { + if (me.kd[s] == KD_PREFIX || me.kd[s] == KD_PATCH) { + store_x(s); + } + } + } +} + +// ------------------------------------------------------------------ attention of block l +// Jobs (me_sched.hpp): the grid column x runs jobs x, x + C, ... ; its reader (last row) reads each K / V chunk of +// the job's segment from DRAM once and multicasts it down the column; every core grants a CB_KV slot (credit) +// before the reader may fill it. Job g's q reads and K / V chunks are issued before job g - 1's outputs are +// collected (CB_AQ holds 2 jobs' q, CB_AO one job's outputs). +uint32_t kv_count = 0; // K / V chunks of this column so far (identical on its cores) + +void kv_chunk(const Item& it, uint32_t p0, uint32_t nk) { + cb_reserve_back(CB_KV, 4 * KC); + const uint32_t ak = get_write_ptr(CB_KV), av = ak + 2 * KC * T16; + if (me.role & R_KVR) { + const uint32_t ka = ca(K_K), va = ca(K_V); + for (uint32_t j = 0; j < nk; ++j) { + const uint32_t key = seg_key(it, p0 + j); + rd16(ka, key * DT + 2 * it.h, ak + (2 * j) * T16); + rd16(ka, key * DT + 2 * it.h + 1, ak + (2 * j + 1) * T16); + rd16(va, key * DT + 2 * it.h, av + (2 * j) * T16); + rd16(va, key * DT + 2 * it.h + 1, av + (2 * j + 1) * T16); + } + for (uint32_t y = 0; y + 1 < R; ++y) { + wait_ge(W_KCRED + y, kv_count + 1); + } + noc_async_read_barrier(); + if (R > 1) { + const uint32_t kx = rt(A_KRX), y0 = rt(A_KY0), y1 = rt(A_KY1); + noc_async_write_multicast(ak, mcast_addr(kx, y0, kx, y1, ak), 2 * nk * T16, R - 1, true); + noc_async_write_multicast(av, mcast_addr(kx, y0, kx, y1, av), 2 * nk * T16, R - 1, true); + const uint32_t srcw = sync_addr(W_KSRC); + *reinterpret_cast(srcw) = kv_count + 1; + noc_semaphore_set_multicast(srcw, mcast_addr(kx, y0, kx, y1, sync_addr(W_KV)), R - 1); + noc_async_writes_flushed(); + } + } else { + noc_semaphore_inc(get_noc_addr(rt(A_KRX), rt(A_KRY), sync_addr(W_KCRED + me.y)), 1); + wait_ge(W_KV, kv_count + 1); + } + ++kv_count; + cb_push_back(CB_KV, 4 * KC); +} + +void att_reads(const Item& it) { + const uint32_t qa = ca(K_Q); + cb_reserve_back(CB_AQ, QB * 2); + { + const uint32_t a = get_write_ptr(CB_AQ); + for (uint32_t j = 0; j < it.nq; ++j) { + rd16(qa, it.q[j] * DT + 2 * it.h, a + (2 * j) * T16); + rd16(qa, it.q[j] * DT + 2 * it.h + 1, a + (2 * j + 1) * T16); + } + } + noc_async_read_barrier(); + cb_push_back(CB_AQ, QB * 2); + const uint32_t L = seg_len(it); + for (uint32_t p0 = 0; p0 < L; p0 += KC) { + kv_chunk(it, p0, L - p0 < KC ? L - p0 : KC); + } +} +void att_writes(const Item& it) { + const uint32_t oa = ca(K_O); + for (uint32_t j = 0; j < it.nq; ++j) { + cb_wait_front(CB_AO, 2); + const uint32_t a = get_read_ptr(CB_AO); + wr16(oa, it.q[j] * DT + 2 * it.h, a); + wr16(oa, it.q[j] * DT + 2 * it.h + 1, a + T16); + noc_async_writes_flushed(); + cb_pop_front(CB_AO, 2); + } +} +void att_dm(uint32_t l) { + Item it[2]; + const uint32_t n = n_jobs(l); + uint32_t k = 0; + for (uint32_t g = me.x; g < n; g += C, ++k) { + job_of(l, g, me.y, it[k & 1]); + att_reads(it[k & 1]); + if (k > 0) { + att_writes(it[(k - 1) & 1]); + } + } + if (k > 0) { + att_writes(it[(k - 1) & 1]); + } + noc_async_atomic_barrier(); +} + +} // namespace + +void kernel_main() { + load_args(); + for (uint32_t w = 0; w < N_SYNC; ++w) { + *sync_ptr(w) = 0; + } +#if ME_PROF + for (uint32_t w = 0; w < PROF_WORDS; ++w) { + prof_ptr()[w] = 0; + } +#endif + boot_barrier(); + PROF(0); + init_consts(); + const uint32_t nl = me.nl; + dbg(1, 0); + // E: embedding (+ LN1 / QKV of block 0) + for (uint32_t w = 0; w < NW; ++w) { + kinds(w); + rope_tab(); + uint32_t act = 0; + for (uint32_t s = 0; s < RB; ++s) { + act |= (me.kd[s] == KD_PATCH ? 1u : 0u) << s; + } + ia_gather(0, act); + tail_dm(-1); + wave_end_dm(NW > 1 || (me.dump && nl == 0)); + } + PROF(1); + for (uint32_t l = 0; l < nl; ++l) { + barrier(); + PROF(2 + 4 * l); + dbg(2, l); + att_dm(l); + PROF(3 + 4 * l); + barrier(); + PROF(4 + 4 * l); + dbg(3, l); + for (uint32_t w = 0; w < NW; ++w) { + kinds(w); + rope_tab(); + if (NW > 1) { + x_load(); + } + uint32_t act = 0; + for (uint32_t s = 0; s < RB; ++s) { + act |= (mlp_on(l, me.kd[s]) ? 1u : 0u) << s; + } + const bool wp = l == 1 && w == 0; + if (wp) PROF(320); + if (NW > 1 && l + 1 >= NL && w > 0) { + // a block without a QKV tail: before this wave's attention output lands in CB_INF, every row core must + // have finished the previous wave's FC2 reads of it (the tail's LN1 gather orders this otherwise) + wait_all(W_FD, C, gen_fd); + } + ia_gather(1, act); + if (wp) PROF(321); + ln_gather(); + if (wp) PROF(322); + fc1_gather(); + if (NW > 1 && l + 1 >= NL && w + 1 < NW) { + cb_wait_front(CB_TOK, 1); + cb_pop_front(CB_TOK, 1); + row_flag(W_FD + me.x, SRC_FD, ++gen_fd); + } + if (wp) PROF(323); + const int tk = tap_of(l); + if (tk >= 0) { + tap_dm((uint32_t)tk); + } + tail_dm((int)l); + if (wp) PROF(324); + wave_end_dm(NW > 1 || (me.dump && l + 1 == nl)); + } + PROF(5 + 4 * l); + } +#if ME_PROBE + if (me.idx == 0 && nl > 0) { + cb_wait_front(CB_PRB, N_PROBE); + const uint32_t a = get_read_ptr(CB_PRB); + for (uint32_t i = 0; i < N_PROBE; ++i) { + wr32(ca(K_PROBE), i, a + i * T32); + } + noc_async_write_barrier(); + cb_pop_front(CB_PRB, N_PROBE); + } +#endif + dbg(0xD0, 0xD0); + noc_async_full_barrier(); +#if ME_PROF + for (volatile uint32_t spin = 0; spin < 20000; spin = spin + 1) { // let the TRISC's last stamps land + } + noc_async_write_page(me.idx, TensorAccessor(acc_dram, ca(K_PROF), PROF_WORDS * 4), cb_base(CB_SYNC) + SYNC_PROF); + noc_async_write_barrier(); +#endif +} diff --git a/code/tt_depthpro2/tt/mk_enc/kernels/me_defs.hpp b/code/tt_depthpro2/tt/mk_enc/kernels/me_defs.hpp new file mode 100644 index 0000000000000000000000000000000000000000..048c71c1f91686b06c65c58a4652e575a1cc09b3 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_enc/kernels/me_defs.hpp @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// DepthPro2 ENC megakernel: fixed ids shared by the three RISC kernels AND the host (geometry.py parses every +// `constexpr uint32_t NAME = ;` line of this file; one definition per line, integer literals only). +// Shape-dependent constants (ME_*) come from kernel defines generated by geometry.py. +#pragma once +#include + +namespace mex { + +// host <-> kernel interface version: bump on EVERY change of the CB ids, sync words, runtime / common args or constant +// tiles. geometry.py passes the value it parsed at import as ME_ABI_HOST: kernel sources edited under a running +// process (serve-pkg smoke 2026-11-28 22:10: T > 1 programs read a common arg the old host did not pass) fail to +// compile instead of computing garbage. +constexpr uint32_t ME_ABI = 3; +#if defined(ME_ABI_HOST) +static_assert(ME_ABI == ME_ABI_HOST, "mk_enc: kernel sources differ from the host code this process imported (edited " + "after import): restart the process"); +#endif + +// ---------------------------------------------------------------- circular buffers +constexpr uint32_t CB_W = 0; // bf16 weight ring (NCRISC -> TRISC), pages of PAGE_TILES +constexpr uint32_t CB_INX = 1; // bf16 [RB * DT] LN input bf16(x) of the slots, k-major (k * RB + s); row gather +constexpr uint32_t CB_INF = 2; // bf16 [RB * max(FT, DT, PE_T)]: patches / attention output (k * RB + s) or FC1 output + // (f * RB + s); row gathers +constexpr uint32_t CB_STAT = 3; // fp32 [C] landing: the row's packed partial-statistics tiles (FPU operand) +constexpr uint32_t CB_X = 4; // fp32 [2 * RB * NXM] residual x of the slots, s * NXM + j (UnpackToDestFp32) +constexpr uint32_t CB_SUMS = 5; // fp32 [4 * RB] per slot: sum_j x_j, sum_j x_j^2, each as hi / lo (FPU operand) +constexpr uint32_t CB_STO = 6; // fp32 [1] this core's packed partial statistics (BRISC ships it) +constexpr uint32_t CB_OUTX = 7; // bf16 [NXM * RB] bf16(x) slice for the LN gather, j * RB + s +constexpr uint32_t CB_EXT = 8; // bf16 [RB] the LN-fold extra K tile per slot: cols 0 / 1 = -mu hi / lo, 2 / 3 = std hi / lo +constexpr uint32_t CB_RSTD = 9; // fp32 [RB] rstd per slot, broadcast over the columns (UnpackToDestFp32) +constexpr uint32_t CB_RAW = 10; // fp32 [8] raw matmul accumulators for the epilogues (UnpackToDestFp32) +constexpr uint32_t CB_OUT = 11; // bf16 [2 x 2 * RB] QKV unit outputs, s * 2 + d (BRISC -> q / k / v staging), 2 units +constexpr uint32_t CB_FO = 12; // bf16 [2 x FB * RB] FC1 output blocks, jj * RB + s (BRISC multicasts them) +constexpr uint32_t CB_CONST = 13; // bf16 constants (C_*) +constexpr uint32_t CB_CF32 = 14; // fp32 constants (F_*) (UnpackToDestFp32) +constexpr uint32_t CB_TAB = 15; // fp32 [2 * RB] rope tables of the slots: s * 2 + {cos, sin} (UnpackToDestFp32) +constexpr uint32_t CB_XO = 16; // fp32 [NXM] x slice of one slot to store (XD) (TRISC -> BRISC) +constexpr uint32_t CB_TAP = 17; // bf16 [NXM] x slice of one slot for a tap (TRISC -> BRISC) +constexpr uint32_t CB_PL = 18; // fp32 [NXM] pool input: one frame's prefix x slice (BRISC -> TRISC) +constexpr uint32_t CB_PFX = 19; // fp32 [NXM] the prefix-token constant (cls / reg rows) of this column's slice +constexpr uint32_t CB_XL = 20; // fp32 [RB * NXM] x of the wave loaded from XD (BRISC -> TRISC) +constexpr uint32_t CB_AQ = 21; // bf16 [QB * 2] attention item q tiles +constexpr uint32_t CB_KV = 22; // bf16 view of CB_INF's memory (attention phase): K / V chunks of 4 KC tiles + // (K j * 2 + d, V 2 KC + j * 2 + d) +constexpr uint32_t CB_S32F = 24; // fp32 view of the score region (attention): FPU operand of the row-max reduce +constexpr uint32_t CB_MX = 25; // fp32 [1] row max (column vector; FPU operand of the broadcast) +constexpr uint32_t CB_MFN = 26; // fp32 [3] m_new, alpha, shift of P (broadcast over the columns) (UnpackToDestFp32) +constexpr uint32_t CB_AP = 27; // fp32 view of the score region (attention): P = exp(S - m), KC tiles (FPU operand; a bf16 + // P failed the hypersensitive img_375x500_pad gates, MK_LOG round 5) +constexpr uint32_t CB_ST = 28; // fp32 view of CB_INX's memory (attention phase): online-softmax state FIFO, 4 tiles per + // q tile: O0, O1, l, m (UnpackToDestFp32) +constexpr uint32_t CB_AO = 29; // bf16 [2 * 2] attention output of one q tile (TRISC -> BRISC) +constexpr uint32_t CB_SYNC = 30; // raw: sync words +constexpr uint32_t CB_TOK = 31; // bf16 [1] TRISC -> BRISC token (debug dump points) +constexpr uint32_t CB_PRB = 32; // fp32 [N_PROBE] debug probes (ME_PROBE builds: TRISC -> BRISC -> K_PROBE) +constexpr uint32_t N_PROBE = 24; +constexpr uint32_t CB_S32 = 33; // fp32 score region (attention; shares CB_RAW's memory, max(8, KC) tiles): S (or D = S - m1), + // read by copy (UnpackToDestFp32); views CB_S32F / CB_AP; P overwrites S in place. + // Every view pushes / pops exactly KC tiles per use, so all stay at the region base. +constexpr uint32_t CB_MF1 = 34; // fp32 [1] first-step row max m1, broadcast (UnpackToDestFp32) +constexpr uint32_t CB_SC = 35; // fp32 [6] LN statistics of the slots in columns s: mu, rstd, std, each hi / lo (FPU operand) + +// ---------------------------------------------------------------- constants (CB_CONST bf16 tile index) +constexpr uint32_t C_ONES = 0; // all ones (row sums, max reduce scaler) +constexpr uint32_t C_E0 = 1; // ones in column 0: in0 of a bias-only extra K tile +constexpr uint32_t C_L0 = 2; // 2 .. 2 + 2 RB_MAX - 1: ones in column q (packs per-slot row sums into column q) +constexpr uint32_t C_SEL0 = 10; // 10 .. 10 + 2 RB_MAX - 1: ones in row q (selects column q, broadcast over columns) +constexpr uint32_t C_PA = 18; // columns 2s and 8 + 2s -> s (hi + lo of the per-slot row sums of x to column s) +constexpr uint32_t C_PB = 19; // columns 2s + 1 and 8 + 2s + 1 -> s (row sums of x^2) +constexpr uint32_t C_PM0 = 20; // 20 .. 23: -1 at (s, 0): mu hi (column s) -> -mu hi in column 0 +constexpr uint32_t C_PS0 = 24; // 24 .. 27: 1 at (s, 2): std hi (column s) -> std hi in column 2 +constexpr uint32_t C_I = 28; // identity +constexpr uint32_t C_SH8 = 29; // column k -> k + 8 (k < 8): the lo half of a packed statistics tile +constexpr uint32_t C_PM1 = 30; // 30 .. 33: -1 at (s, 1): mu lo -> column 1 +constexpr uint32_t C_PS1 = 34; // 34 .. 37: 1 at (s, 3): std lo -> column 3 +constexpr uint32_t N_CONST = 38; +constexpr uint32_t RB_MAX = 4; +// fp32 constants (CB_CF32 tile index) +constexpr uint32_t F_NEG0 = 0; // -1 in column 0 +constexpr uint32_t F_ONE1 = 1; // 1 in column 1 +constexpr uint32_t F_MASKP = 2; // 0 in columns < 5, -1e9 elsewhere (prefix / pool key tile) +constexpr uint32_t F_MASKN = 3; // 0 in columns < NLAST, -1e9 elsewhere (a frame's last patch key tile) +constexpr uint32_t F_ZERO = 4; // zeros +constexpr uint32_t N_CF32 = 5; + +// ---------------------------------------------------------------- sync words (CB_SYNC, SYNC_STRIDE bytes apart) +constexpr uint32_t SYNC_STRIDE = 16; +constexpr uint32_t W_BAR = 0; // every core: global barrier generation (hub multicast) +constexpr uint32_t W_BCNT = 1; // hub: barrier arrivals (cumulative) +constexpr uint32_t W_WVAL = 2; // ring receiver: weight pages valid (feeder multicast, cumulative) +constexpr uint32_t W_POOL = 3; // pool owner: prefix slices landed in XD (cumulative) +constexpr uint32_t W_CRED = 4; // feeder: 4 + y = pages receiver row y has room for (cumulative), y < 16 +constexpr uint32_t W_IX = 20; // 20 + x: LN gather round of column x landed (generation) +constexpr uint32_t W_IA = 36; // 36 + x: INF in0 gather (patches / attention output) of column x landed +constexpr uint32_t W_IF = 52; // 52 + x: FC1 output gather of column x landed +constexpr uint32_t W_SRC = 68; // 68 .. 75: local source words of the flag multicasts +constexpr uint32_t SRC_IX = 0; +constexpr uint32_t SRC_IA = 1; +constexpr uint32_t SRC_IF = 2; +constexpr uint32_t SRC_BAR = 3; +constexpr uint32_t W_DBG = 76; // 76 .. 79: debug words +constexpr uint32_t W_SRCV = 80; // 80 .. 87: the feeder's source words of the W_WVAL multicasts (ring of 8) +constexpr uint32_t N_SRCV = 8; +constexpr uint32_t W_KV = 88; // column K / V chunks landed (attention; the column reader's multicast, cumulative) +constexpr uint32_t W_KSRC = 89; // the reader's source word of that flag +constexpr uint32_t W_KCRED = 90; // 90 + y: K / V chunk slots receiver row y granted (at the reader, cumulative), y < 15 +constexpr uint32_t W_FD = 106; // 106 + x: column x finished its FC2 reads of CB_INF (waves of a block without a QKV tail: + // the next wave's attention-output gather may land; MK_LOG round 5) +constexpr uint32_t SRC_FD = 4; // its local source word (W_SRC + 4) +constexpr uint32_t W_NV = 122; // valid frames n of this run (T > 1: the BRISC reads the VF tensor at start; the + // TRISC gets it through the unpack thread's mailbox, set_valid_frames) +constexpr uint32_t W_INVN = 123; // fp32 bits of 1 / n (pooled-prefix mean) +constexpr uint32_t N_SYNC = 124; +constexpr uint32_t SYNC_PROF = 1984; // byte offset of the ME_PROF time stamps (BRISC 0..191, TRISC att 192..255, + // TRISC wave detail 256..319, BRISC wave detail 320..383) +constexpr uint32_t PROF_WORDS = 512; +constexpr uint32_t SYNC_BYTES = 4032; // N_SYNC * SYNC_STRIDE + PROF_WORDS * 4 + +// ---------------------------------------------------------------- roles (A_ROLE bits) +constexpr uint32_t R_FEED = 1; // weight feeder of its column (grid row 0) +constexpr uint32_t R_HUB = 2; // global barrier hub +constexpr uint32_t R_KVR = 4; // K / V reader of its column (last grid row) + +// ---------------------------------------------------------------- per-core runtime args +constexpr uint32_t A_IDX = 0; +constexpr uint32_t A_ROLE = 1; +constexpr uint32_t A_X = 2; +constexpr uint32_t A_Y = 3; +constexpr uint32_t A_H0 = 4; // first QKV head unit of the column +constexpr uint32_t A_NH = 5; +constexpr uint32_t A_N0 = 6; // first proj / fc2 / embed output tile +constexpr uint32_t A_NX = 7; +constexpr uint32_t A_F0 = 8; // first FC1 hidden tile (SwiGLU: pair) +constexpr uint32_t A_NF = 9; +constexpr uint32_t A_KS0 = 10; // this core's share [KS0, KS1) of the DT tiles of an attention-output row gather +constexpr uint32_t A_KS1 = 11; +constexpr uint32_t A_PK0 = 12; // this core's share [PK0, PK1) of the PE_T tiles of a patch row gather +constexpr uint32_t A_PK1 = 13; +constexpr uint32_t A_ROWX0 = 14; // NoC x of logical columns 0 / C - 1 (row rectangle) +constexpr uint32_t A_ROWX1 = 15; +constexpr uint32_t A_ROWY = 16; // NoC y of this core's row +constexpr uint32_t A_FX = 17; // NoC x / y of the column feeder +constexpr uint32_t A_FY = 18; +constexpr uint32_t A_COLY0 = 19; // feeder: NoC y of rows 1 / R - 1 of its column (multicast rectangle) +constexpr uint32_t A_COLY1 = 20; +constexpr uint32_t A_POOLX = 21; // NoC x / y of the pool owner of this column +constexpr uint32_t A_POOLY = 22; +constexpr uint32_t A_P0E = 23; // first page of this column in the embed arena / pages +constexpr uint32_t A_NPE = 24; +constexpr uint32_t A_P0B = 25; // first page of this column in a block arena / pages (blocks 0 .. L - 2) +constexpr uint32_t A_NPB = 26; +constexpr uint32_t A_P0BL = 27; // the last block's arena (no QKV) +constexpr uint32_t A_NPBL = 28; +constexpr uint32_t A_KRX = 29; // NoC x / y of the column's K / V reader +constexpr uint32_t A_KRY = 30; +constexpr uint32_t A_KY0 = 31; // reader: NoC y of rows 0 / R - 2 of its column (multicast rectangle) +constexpr uint32_t A_KY1 = 32; +constexpr uint32_t N_RT_ARGS = 33; + +// ---------------------------------------------------------------- common runtime args +constexpr uint32_t K_ALL_X0 = 0; // whole-grid rectangle (NoC) +constexpr uint32_t K_ALL_Y0 = 1; +constexpr uint32_t K_ALL_X1 = 2; +constexpr uint32_t K_ALL_Y1 = 3; +constexpr uint32_t K_N_ALL = 4; +constexpr uint32_t K_HUB_X = 5; +constexpr uint32_t K_HUB_Y = 6; +constexpr uint32_t K_NL = 7; // blocks run (L = the whole encoder; fewer = debug) +constexpr uint32_t K_DUMP = 8; // 1: store x (fp32) to XD after the last block run (debug) +constexpr uint32_t K_EPS = 9; // fp32 bits of the LN eps +constexpr uint32_t K_INVD = 10; // fp32 bits of 1 / dim +constexpr uint32_t K_INVT = 11; // fp32 bits of 1 / T (T = 1 or no pool; else 1 / n comes with the VF tensor) +constexpr uint32_t K_PATCH = 12; // patches [T * Np, 768] bf16 TILE +constexpr uint32_t K_TAP0 = 13; // 13 .. 16: taps +constexpr uint32_t K_XD = 17; // x residual fp32 [Mt * 32, D] TILE +constexpr uint32_t K_Q = 18; // q / k / v / attention-output staging, bf16 [Mt * 32, D] TILE +constexpr uint32_t K_K = 19; +constexpr uint32_t K_V = 20; +constexpr uint32_t K_O = 21; +constexpr uint32_t K_CONST = 22; // bf16 constants [N_CONST * 32, 32] TILE +constexpr uint32_t K_CF32 = 23; // fp32 constants [N_CF32 * 32, 32] TILE +constexpr uint32_t K_ROPE = 24; // fp32 [Pt * 32, 64] TILE: tile (p, 0) = cos, (p, 1) = sin +constexpr uint32_t K_PFX = 25; // fp32 [32, D] TILE: prefix-token rows (cls, reg0..3), 0 elsewhere +constexpr uint32_t K_ARENA_E = 26; +constexpr uint32_t K_ARENA0 = 27; // 27 .. 27 + L - 1: block arenas +constexpr uint32_t K_PROBE = 59; // fp32 [N_PROBE * 32, 32] TILE debug probes +constexpr uint32_t K_PROF = 60; // uint32 [NC, PROF_WORDS] ROW_MAJOR time stamps (ME_PROF builds) +constexpr uint32_t K_VF = 61; // uint32 [32, 32] TILE: element 0 = valid frames n, element 1 = fp32 bits of 1 / n +constexpr uint32_t N_COMMON_ARGS = 62; + +// ---------------------------------------------------------------- compile-time args +constexpr uint32_t CT_ACC0 = 0; // TensorAccessorArgs (DRAM interleaved; page size given per use) + +} // namespace mex diff --git a/code/tt_depthpro2/tt/mk_enc/kernels/me_dm.hpp b/code/tt_depthpro2/tt/mk_enc/kernels/me_dm.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6f36eed8c207219218c697a5c74f0be5107bb878 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_enc/kernels/me_dm.hpp @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// DepthPro2 ENC megakernel: data-movement helpers shared by the BRISC and NCRISC kernels (mk_vision's mv_dm.hpp). +#pragma once + +#include +#include "api/dataflow/dataflow_api.h" +#include "api/debug/waypoint.h" +#include "me_sched.hpp" + +namespace mex { + +constexpr uint32_t T16 = 2048, T32 = 4096; +constexpr uint32_t PAGE_BYTES = PAGE_TILES * T16; + +FORCE_INLINE uint32_t rt(uint32_t i) { return get_arg_val(i); } +FORCE_INLINE uint32_t ca(uint32_t i) { return get_common_arg_val(i); } + +// Byte address of a CB's buffer base (LocalCBInterface keeps it in 16 B units): identical on every core. +FORCE_INLINE uint32_t cb_base(uint32_t cb) { + const auto& iface = get_local_cb_interface(cb); + return (iface.fifo_limit - iface.fifo_size) << cb_addr_shift; +} + +FORCE_INLINE uint32_t sync_addr(uint32_t w) { return cb_base(CB_SYNC) + w * SYNC_STRIDE; } +FORCE_INLINE volatile tt_l1_ptr uint32_t* sync_ptr(uint32_t w) { + return reinterpret_cast(sync_addr(w)); +} +FORCE_INLINE uint32_t sync_read(uint32_t w) { + invalidate_l1_cache(); + asm volatile("" ::: "memory"); + return *sync_ptr(w); +} + +// Multicast NoC address of the rectangle (x0, y0)-(x1, y1) given in NoC-0 virtual coordinates (start = min corner); +// NoC 1 addresses the rectangle end-first. +FORCE_INLINE uint64_t mcast_addr(uint32_t x0, uint32_t y0, uint32_t x1, uint32_t y1, uint32_t addr) { + if (noc_index == 0) { + return NOC_MULTICAST_ADDR( + DYNAMIC_NOC_X(0, x0), DYNAMIC_NOC_Y(0, y0), DYNAMIC_NOC_X(0, x1), DYNAMIC_NOC_Y(0, y1), addr); + } + return NOC_MULTICAST_ADDR( + DYNAMIC_NOC_X(1, x1), DYNAMIC_NOC_Y(1, y1), DYNAMIC_NOC_X(1, x0), DYNAMIC_NOC_Y(1, y0), addr); +} + +// Pages of the weight ring the TRISC has fully consumed, from the CB's received / acked tile counters (16-bit). +FORCE_INLINE uint32_t ring_outstanding_tiles() { + invalidate_l1_cache(); + asm volatile("" ::: "memory"); + const uint16_t received = (uint16_t)get_cb_tiles_received_ptr(CB_W)[0]; + const uint16_t acked = (uint16_t)reg_read((uintptr_t)get_cb_tiles_acked_ptr(CB_W)); + return (uint16_t)(received - acked); +} + +// boot barrier: every core zeroed its sync words before anyone exchanges (semaphores reset at program launch) +FORCE_INLINE void wait_go(uint32_t sem_go_addr) { + volatile tt_l1_ptr uint32_t* go = reinterpret_cast(sem_go_addr); + WAYPOINT("BGO "); + while (true) { + invalidate_l1_cache(); + if (*go >= 1) { + break; + } + } +} + +#if ME_PROF +FORCE_INLINE volatile tt_l1_ptr uint32_t* prof_ptr() { + return reinterpret_cast(cb_base(CB_SYNC) + SYNC_PROF); +} +#define PROF(i) (mex::prof_ptr()[(i)] = get_timestamp_32b()) +#else +#define PROF(i) \ + do { \ + } while (0) +#endif + +} // namespace mex diff --git a/code/tt_depthpro2/tt/mk_enc/kernels/me_ncrisc.cpp b/code/tt_depthpro2/tt/mk_enc/kernels/me_ncrisc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dbf55c3fabd3cd2b53a670f012be794054cddb6d --- /dev/null +++ b/code/tt_depthpro2/tt/mk_enc/kernels/me_ncrisc.cpp @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// DepthPro2 ENC megakernel, NCRISC (NoC 0): the weight ring (mk_vision's mv_ncrisc.cpp protocol). +// feeder (x, 0): reads its column's pages segment by segment (embed arena x W waves, then block l's arena x W waves +// for l < nl) from DRAM straight into its own ring slot, pushes them for its own TRISC and multicasts +// each page to the same slot of rows 1 .. R - 1 of its column, then the cumulative valid count +// (W_WVAL). A page goes out only when every receiver granted it (per-receiver credits W_CRED + y). +// receiver : grants ring slots as its TRISC frees them and pushes the pages the feeder flagged valid. +#include "me_dm.hpp" + +using namespace mex; + +namespace { + +constexpr auto acc_dram = TensorAccessorArgs(); +#ifndef ME_RING_DEPTH +#define ME_RING_DEPTH 4 +#endif +constexpr uint32_t DEPTH = ME_RING_DEPTH; +constexpr uint32_t SLOTS = RING; + +FORCE_INLINE uint32_t freed_pages(uint32_t pushed) { + const uint32_t out = ring_outstanding_tiles(); + return pushed - (out + PAGE_TILES - 1) / PAGE_TILES; +} + +void receiver(uint32_t total) { + const uint32_t y = rt(A_Y); + const uint64_t cred = get_noc_addr(rt(A_FX), rt(A_FY), sync_addr(W_CRED + y)); + uint32_t granted = 0, pushed = 0; + while (pushed < total) { + WAYPOINT("NRCV"); + if (granted < total) { + uint32_t lim = freed_pages(pushed) + SLOTS; + if (lim > total) { + lim = total; + } + if (lim > granted) { + noc_semaphore_inc(cred, lim - granted); + granted = lim; + } + } + const uint32_t v = sync_read(W_WVAL); + if (v > pushed) { + cb_push_back(CB_W, (v - pushed) * PAGE_TILES); + pushed = v; + } + } + noc_async_atomic_barrier(); +} + +// segment s -> (arena address, first page of this column, pages): W embed segments, then W per block +struct Seg { + uint32_t addr, p0, np; +}; +FORCE_INLINE Seg seg_of(uint32_t s) { + if (s < NW) { + return {ca(K_ARENA_E), rt(A_P0E), rt(A_NPE)}; + } + const uint32_t l = (s - NW) / NW; + if (l == NL - 1) { + return {ca(K_ARENA0 + l), rt(A_P0BL), rt(A_NPBL)}; + } + return {ca(K_ARENA0 + l), rt(A_P0B), rt(A_NPB)}; +} + +void feeder(uint32_t total) { + const uint32_t fx = rt(A_FX), y0 = rt(A_COLY0), y1 = rt(A_COLY1); + constexpr uint32_t nrecv = R - 1; + const uint32_t base = cb_base(CB_W); + const uint32_t wval = sync_addr(W_WVAL); + uint32_t rd_issued = 0, rd_done = 0, mc_done = 0, mc_flushed = 0; + uint32_t s = 0, lp = 0; + Seg seg = seg_of(0); + while (mc_done < total || rd_done < total) { + WAYPOINT("NFED"); + if (rd_done < rd_issued && ncrisc_noc_read_with_transaction_id_flushed(noc_index, 1 + (rd_done % DEPTH))) { + invalidate_l1_cache(); + ++rd_done; + cb_push_back(CB_W, PAGE_TILES); + } + if (mc_done < rd_done) { + uint32_t mn = 0xFFFFFFFFu; + for (uint32_t r = 1; r <= nrecv; ++r) { + const uint32_t c = sync_read(W_CRED + r); + mn = c < mn ? c : mn; + } + if (mn > mc_done) { + if (mc_done - mc_flushed >= N_SRCV) { + noc_async_writes_flushed(); + mc_flushed = mc_done; + } + const uint32_t a = base + (mc_done % SLOTS) * PAGE_BYTES; + const uint32_t src = sync_addr(W_SRCV + (mc_done % N_SRCV)); + noc_async_write_multicast(a, mcast_addr(fx, y0, fx, y1, a), PAGE_BYTES, nrecv, true); + *reinterpret_cast(src) = mc_done + 1; + noc_semaphore_set_multicast(src, mcast_addr(fx, y0, fx, y1, wval), nrecv); + ++mc_done; + } + } + if (rd_issued < total && rd_issued - rd_done < DEPTH && rd_issued < freed_pages(rd_done) + SLOTS) { + bool ok = true; + if (rd_issued >= SLOTS) { + const uint32_t prev = rd_issued - SLOTS; + if (mc_done <= prev) { + ok = false; + } else if (mc_flushed <= prev) { + noc_async_writes_flushed(); + mc_flushed = mc_done; + } + } + if (ok) { + noc_async_read_set_trid(1 + (rd_issued % DEPTH)); + const auto acc = TensorAccessor(acc_dram, seg.addr, PAGE_BYTES); + noc_async_read_page(seg.p0 + lp, acc, base + (rd_issued % SLOTS) * PAGE_BYTES); + ++rd_issued; + if (++lp == seg.np) { + lp = 0; + ++s; + if (rd_issued < total) { + seg = seg_of(s); + } + } + } + } + } + noc_async_read_set_trid(0); + noc_async_write_barrier(); +} + +} // namespace + +void kernel_main() { + const uint32_t role = rt(A_ROLE); + wait_go(get_semaphore(1)); // SEM_GO: the BRISCs zeroed every sync word + const uint32_t nl = ca(K_NL); + uint32_t total = NW * rt(A_NPE); + for (uint32_t l = 0; l < nl; ++l) { + total += NW * (l == NL - 1 ? rt(A_NPBL) : rt(A_NPB)); + } + if (role & R_FEED) { + feeder(total); + } else { + receiver(total); + } +} diff --git a/code/tt_depthpro2/tt/mk_enc/kernels/me_sched.hpp b/code/tt_depthpro2/tt/mk_enc/kernels/me_sched.hpp new file mode 100644 index 0000000000000000000000000000000000000000..628df6875aefd0daed3042e5771d4e6afb87d900 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_enc/kernels/me_sched.hpp @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// DepthPro2 ENC megakernel: the schedule shared by the BRISC and the TRISC (both walk it in the same order) and the +// shape constants (ME_* defines from geometry.py). +#pragma once +#include +#include "me_defs.hpp" + +#define ME_INL inline __attribute__((always_inline)) + +namespace mex { + +constexpr uint32_t DT = ME_DT; // hidden tiles (dim / 32) +constexpr uint32_t FT = ME_FT; // MLP hidden tiles (SwiGLU: pairs) +constexpr uint32_t NH = ME_H; // heads +constexpr uint32_t NL = ME_L; // blocks +constexpr bool SWIGLU = ME_SWIGLU != 0; +constexpr uint32_t C = ME_C; // grid columns +constexpr uint32_t R = ME_R; // grid rows +constexpr uint32_t RB = ME_RB; // slots per row and wave +constexpr uint32_t T = ME_T; // frames +constexpr uint32_t PT = ME_PT; // patch tiles per frame +constexpr uint32_t NLAST = ME_NLAST; // valid rows of a frame's last patch tile +constexpr uint32_t NW = ME_W; // waves +constexpr bool POOL = ME_POOL != 0; // pool tile exists (T > 1 with joint blocks) +constexpr uint32_t MT = ME_MT; // row tiles +constexpr uint32_t QB = ME_QB; // q tiles per attention item +constexpr uint32_t KC = ME_KC; // key tiles per chunk +constexpr uint32_t JOINT = ME_JOINT; // bit l: cross-frame joint attention (depth mode) +constexpr uint32_t FREEZE = ME_FREEZE; // bit l: prefix frozen +constexpr uint32_t GIANT = ME_GIANT; // bit l: two-step (fp32-accurate) attention row max +constexpr bool FOV = ME_FOV != 0; // taps include the prefix tiles (FOV trunk) +constexpr uint32_t NXM = ME_NXM; +constexpr uint32_t G = ME_G; // proj / fc2 / embed n-group width +constexpr uint32_t FB = ME_FB; // FC1 f-block width +constexpr uint32_t RING = ME_RING; // weight ring pages +constexpr uint32_t NCORE = ME_NC; +constexpr uint32_t INX_CAP = ME_INXT; // CB_INX FIFO cycles are its whole capacity (>= RB * DT; CB_ST views it) +constexpr uint32_t INF_CAP = ME_INFT; // CB_INF FIFO cycles are its whole capacity (pointers stay at the base) +constexpr uint32_t PE_T = 24; // patch K tiles +constexpr uint32_t PAGE_TILES = 8; +constexpr uint32_t NPATCH = T * PT; // patch tiles +constexpr uint32_t RI_POOL = MT - 1; +constexpr uint32_t SPECIAL_JOINT = POOL ? RI_POOL : 0; // the joint segment's prefix key tile +static_assert(RB <= RB_MAX, "slots"); +static_assert(2 * RB <= 8, "QKV unit accumulators"); +static_assert((KC == 8 || KC == 16 || KC == 32) && QB >= 1, "attention blocking"); + +enum Kind : uint32_t { KD_PREFIX = 0, KD_PATCH = 1, KD_POOL = 2, KD_EMPTY = 3 }; + +ME_INL uint32_t ri_of(uint32_t w, uint32_t y, uint32_t s) { return (w * RB + s) * R + y; } +ME_INL uint32_t kind_of(uint32_t ri) { + if (ri < T) { + return KD_PREFIX; + } + if (ri < T + NPATCH) { + return KD_PATCH; + } + if (POOL && ri == RI_POOL) { + return KD_POOL; + } + return KD_EMPTY; +} +ME_INL bool joint(uint32_t l) { return l < NL && ((JOINT >> l) & 1u); } +ME_INL bool frozen(uint32_t l) { return l < NL && ((FREEZE >> l) & 1u); } +ME_INL bool giant(uint32_t l) { return l < NL && ((GIANT >> l) & 1u); } +ME_INL int tap_of(uint32_t l) { + return l == ME_TAP0 ? 0 : l == ME_TAP1 ? 1 : l == ME_TAP2 ? 2 : l == ME_TAP3 ? 3 : -1; +} + +// QKV unit types of a slot in block l: bit 0 q, bit 1 k, bit 2 v +ME_INL uint32_t qkv_mask(uint32_t l, uint32_t kind) { + if (kind == KD_PATCH) { + return 7u; + } + if (kind == KD_PREFIX) { + if (joint(l)) { + return T == 1 ? 6u : 0u; + } + return frozen(l) ? 6u : 7u; + } + if (kind == KD_POOL) { + return joint(l) ? 6u : 0u; + } + return 0u; +} +// proj / LN2 / MLP of block l run for this slot +ME_INL bool mlp_on(uint32_t l, uint32_t kind) { + return kind == KD_PATCH || (kind == KD_PREFIX && !frozen(l)); +} +// the slot's x is written to a tap after block l +ME_INL bool tap_on(uint32_t kind) { return kind == KD_PATCH || (FOV && kind == KD_PREFIX); } +ME_INL uint32_t tap_row(uint32_t ri) { + if (FOV) { + return ri < T ? ri * (PT + 1) : ((ri - T) / PT) * (PT + 1) + 1 + (ri - T) % PT; + } + return ri - T; +} +// unit u of the fused qkv: type 0 q, 1 k, 2 v; head +ME_INL uint32_t unit_type(uint32_t u) { return u / NH; } +ME_INL uint32_t unit_head(uint32_t u) { return u % NH; } + +// ---------------------------------------------------------------- attention jobs of block l +// pair = (head, segment); a job = up to R * QB q tiles of one pair, spread over one grid column (q tile j of the +// job -> row j % R); the column shares every K / V chunk of the pair's segment (one DRAM read by the column's +// reader, multicast down the column). Job g runs on column g % C in round g / C. +struct Item { + uint32_t h; // head + uint32_t nq; // this core's q tiles (<= QB, may be 0) + uint32_t q[QB]; // their row tiles + uint32_t special; // the segment's prefix key tile + uint32_t k0, nk; // the segment's patch key tiles [k0, k0 + nk) +}; +constexpr uint32_t JQ = R * QB; // q tiles per job + +// valid frames n of this run (runtime, MkEnc.set_valid_frames; T when the program has no pool): the joint keys of a +// cross-frame block are [pool ; patch tiles of frames < n] and the pool is the mean over frames < n; the queries of +// frames >= n still run (their outputs are don't-care). Every RISC sets it before the first attention phase. +inline uint32_t g_nv = T; + +ME_INL uint32_t pair_nq(uint32_t l) { return joint(l) ? NPATCH : PT + (frozen(l) ? 0 : 1); } +ME_INL uint32_t n_pairs(uint32_t l) { return joint(l) ? NH : NH * T; } +ME_INL uint32_t n_jobs(uint32_t l) { return n_pairs(l) * ((pair_nq(l) + JQ - 1) / JQ); } + +// q list index qi of pair (.., t) -> row tile +ME_INL uint32_t pair_q(uint32_t l, uint32_t t, uint32_t qi) { + if (joint(l)) { + return T + qi; + } + return frozen(l) ? T + t * PT + qi : (qi == 0 ? t : T + t * PT + qi - 1); +} + +ME_INL void job_of(uint32_t l, uint32_t g, uint32_t y, Item& it) { + const uint32_t nqp = pair_nq(l); + const uint32_t jpp = (nqp + JQ - 1) / JQ; + const uint32_t p = g / jpp, part = g % jpp; + const uint32_t q0 = part * JQ; + const uint32_t nqj = nqp - q0 < JQ ? nqp - q0 : JQ; + uint32_t t = 0; + if (joint(l)) { + it.h = p; + it.special = SPECIAL_JOINT; + it.k0 = T; + it.nk = g_nv * PT; + } else { + it.h = p / T; + t = p % T; + it.special = t; + it.k0 = T + t * PT; + it.nk = PT; + } + it.nq = 0; + for (uint32_t j = y; j < nqj; j += R) { + it.q[it.nq++] = pair_q(l, t, q0 + j); + } +} + +// key tile list of a segment: position 0 = special, then k0 .. k0 + nk - 1; chunks of KC positions +ME_INL uint32_t seg_len(const Item& it) { return 1 + it.nk; } +ME_INL uint32_t seg_key(const Item& it, uint32_t pos) { return pos == 0 ? it.special : it.k0 + pos - 1; } +// mask of a key tile: 0 none, 1 prefix (cols >= 5), 2 last patch tile of a frame (cols >= NLAST) +ME_INL uint32_t key_mask(uint32_t ri) { + if (ri < T || (POOL && ri == RI_POOL)) { + return 1; + } + if (NLAST < 32 && (ri - T) % PT == PT - 1) { + return 2; + } + return 0; +} + +} // namespace mex diff --git a/code/tt_depthpro2/tt/mk_enc/kernels/me_sfpu.hpp b/code/tt_depthpro2/tt/mk_enc/kernels/me_sfpu.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e4e68d31486cb053dc5ffaaba304d7fd2e7457f5 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_enc/kernels/me_sfpu.hpp @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// DepthPro2 ENC megakernel: custom SFPU routines (MATH thread), called through SFPU_BINARY_CALL_NO_TEMPLATE_ARGS: +// the params wrapper calls each routine once per face (4 faces x 8 row pairs); a / r are DST tile indices +// (one fp32 tile = 32 sfpi rows), as in the VLA-JEPA mk_vision mv_sfpu.hpp. +#pragma once +#include "sfpi.h" +#include "ckernel_sfpu_exp.h" +#include "ckernel_sfpu_sigmoid.h" + +namespace ckernel::sfpu { + +// GELU polynomial (the user's MoGe-2 kernel, gelu_poly_compute_v5.cpp): t = clamp(x, -4, 4), u = t^2 / 16, +// Phi = 0.5 + t P(u) (degree-7 weighted minimax fit of the normal CDF), GELU = x Phi; max |error| vs the exact erf +// GELU 2.1e-4 (fp32 evaluation). Here x = dst[a] * dst[r] (the FC1 epilogue rstd * acc), result fp32 in dst[a]. +inline void me_gelu_init() { + sfpi::vConstFloatPrgm0 = 0.3983510434627533f; + sfpi::vConstFloatPrgm1 = -1.0425554513931274f; + sfpi::vConstFloatPrgm2 = 2.3193752765655518f; +} +inline void me_rgelu(const std::uint32_t a, const std::uint32_t r, const std::uint32_t) { + constexpr std::uint32_t T = 32; + const sfpi::vFloat c7 = sfpi::vFloat(sfpi::sFloat16a(0xafb6u)); +#pragma GCC unroll 1 + for (int d = 0; d < 8; d++) { + sfpi::vFloat x = sfpi::dst_reg[a * T]; + const sfpi::vFloat rs = sfpi::dst_reg[r * T]; + x = x * rs; + sfpi::vFloat t = sfpi::symmetric_clamp(x, 4.0f); + sfpi::vFloat u = t * t; + u = u * 0.0625f; + sfpi::vFloat p = u * c7 + sfpi::vFloat(sfpi::sFloat16a(0x3ae0u)); + p = p * u + sfpi::vFloat(sfpi::sFloat16a(0xc0e2u)); + p = p * u + sfpi::vFloat(sfpi::sFloat16a(0x438fu)); + p = p * u + sfpi::vFloat(sfpi::sFloat16a(0xc341u)); + p = p * u + sfpi::vConstFloatPrgm2; + p = p * u + sfpi::vConstFloatPrgm1; + p = p * u + sfpi::vConstFloatPrgm0; + sfpi::dst_reg[a * T] = x * (t * p + 0.5f); + sfpi::dst_reg++; + } +} + +// exact-statistics split: dst[a] <- hi = bf16-rounded dst[a], dst[lo] <- dst[a] - hi (|lo| <= 2^-9 |x|); an FPU +// operand of hi is exact in tf32 and of lo is off by <= 2^-11 |lo|: hi @ M + lo @ M is fp32-accurate to ~2^-20 +inline void me_split(const std::uint32_t a, const std::uint32_t lo, const std::uint32_t) { + constexpr std::uint32_t T = 32; +#pragma GCC unroll 1 + for (int d = 0; d < 8; d++) { + const sfpi::vFloat x = sfpi::dst_reg[a * T]; + const sfpi::vFloat h = sfpi::convert(x, sfpi::RoundMode::Nearest); + sfpi::dst_reg[a * T] = h; + sfpi::dst_reg[lo * T] = x - h; + sfpi::dst_reg++; + } +} + +// SwiGLU epilogue: dst[g] = silu(dst[g] * dst[r]) * (dst[u] * dst[r]) (needs the silu / sigmoid init) +inline void me_rswiglu(const std::uint32_t g, const std::uint32_t u, const std::uint32_t r) { + constexpr std::uint32_t T = 32; +#pragma GCC unroll 1 + for (int d = 0; d < 8; d++) { + const sfpi::vFloat rs = sfpi::dst_reg[r * T]; + sfpi::vFloat x = sfpi::dst_reg[g * T]; + sfpi::vFloat y = sfpi::dst_reg[u * T]; + x = x * rs; + y = y * rs; + sfpi::dst_reg[g * T] = x * _sfpu_sigmoid_(x) * y; + sfpi::dst_reg++; + } +} + +// QKV epilogue of one head unit (tiles a = d 0..31, a + 1 = d 32..63) with rstd at r, cos at r + 1, sin at r + 2: +// rotate-half RoPE a' = A cos - B sin, b' = B cos + A sin with A = a rstd, B = b rstd +inline void me_rope(const std::uint32_t a, const std::uint32_t r, const std::uint32_t) { + constexpr std::uint32_t T = 32; +#pragma GCC unroll 1 + for (int d = 0; d < 8; d++) { + const sfpi::vFloat rs = sfpi::dst_reg[r * T]; + const sfpi::vFloat c = sfpi::dst_reg[(r + 1) * T]; + const sfpi::vFloat sn = sfpi::dst_reg[(r + 2) * T]; + sfpi::vFloat x = sfpi::dst_reg[a * T]; + sfpi::vFloat y = sfpi::dst_reg[(a + 1) * T]; + x = x * rs; + y = y * rs; + sfpi::dst_reg[a * T] = x * c - y * sn; + sfpi::dst_reg[(a + 1) * T] = y * c + x * sn; + sfpi::dst_reg++; + } +} +// the v unit (no RoPE): a, a + 1 scaled by rstd at r +inline void me_rscale2(const std::uint32_t a, const std::uint32_t r, const std::uint32_t) { + constexpr std::uint32_t T = 32; +#pragma GCC unroll 1 + for (int d = 0; d < 8; d++) { + const sfpi::vFloat rs = sfpi::dst_reg[r * T]; + sfpi::vFloat x = sfpi::dst_reg[a * T]; + sfpi::vFloat y = sfpi::dst_reg[(a + 1) * T]; + sfpi::dst_reg[a * T] = x * rs; + sfpi::dst_reg[(a + 1) * T] = y * rs; + sfpi::dst_reg++; + } +} + +// softmax numerator: dst[a] = exp(dst[a] - dst[m]) (m: the row max broadcast over the columns); EXP21 = exp_21f +// (bf16-accurate, max rel err 1.7e-3, input clamped: masked -1e9 -> 0), else the fp32-accurate exp +template +inline void me_subexp(const std::uint32_t a, const std::uint32_t m, const std::uint32_t) { + constexpr std::uint32_t T = 32; +#pragma GCC unroll 1 + for (int d = 0; d < 8; d++) { + sfpi::vFloat x = sfpi::dst_reg[a * T]; + const sfpi::vFloat mx = sfpi::dst_reg[m * T]; + x = x - mx; + if constexpr (EXP21) { + sfpi::dst_reg[a * T] = _sfpu_exp_21f_bf16_(x); + } else { + sfpi::dst_reg[a * T] = _sfpu_exp_fp32_accurate_(x); + } + sfpi::dst_reg++; + } +} + +// dst[0 .. n) -= dst[m] (the max subtraction alone; ME_EXP 2: the exp is the stock TTI exp_21f per tile) +inline void me_sub_n(const std::uint32_t n, const std::uint32_t m, const std::uint32_t) { + constexpr std::uint32_t T = 32; +#pragma GCC unroll 1 + for (int d = 0; d < 8; d++) { + const sfpi::vFloat mx = sfpi::dst_reg[m * T]; +#pragma GCC unroll 1 + for (std::uint32_t t = 0; t < n; ++t) { + const sfpi::vFloat x = sfpi::dst_reg[t * T]; + sfpi::dst_reg[t * T] = x - mx; + } + sfpi::dst_reg++; + } +} + +// the same on DST tiles 0 .. n - 1 in one call (one params setup per 4 tiles) +template +inline void me_subexp_n(const std::uint32_t n, const std::uint32_t m, const std::uint32_t) { + constexpr std::uint32_t T = 32; +#pragma GCC unroll 1 + for (int d = 0; d < 8; d++) { + const sfpi::vFloat mx = sfpi::dst_reg[m * T]; +#pragma GCC unroll 1 + for (std::uint32_t t = 0; t < n; ++t) { + sfpi::vFloat x = sfpi::dst_reg[t * T]; + x = x - mx; + if constexpr (EXP21) { + sfpi::dst_reg[t * T] = _sfpu_exp_21f_bf16_(x); + } else { + sfpi::dst_reg[t * T] = _sfpu_exp_fp32_accurate_(x); + } + } + sfpi::dst_reg++; + } +} + +} // namespace ckernel::sfpu diff --git a/code/tt_depthpro2/tt/mk_enc/kernels/me_trisc.cpp b/code/tt_depthpro2/tt/mk_enc/kernels/me_trisc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4835f66b09df1a98d7024f54d78b232fc7cf669f --- /dev/null +++ b/code/tt_depthpro2/tt/mk_enc/kernels/me_trisc.cpp @@ -0,0 +1,1325 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// DepthPro2 ENC megakernel, TRISC: all arithmetic (LLK usage from the VLA-JEPA mk_vision megakernel). +// +// Core (x, y) holds RB slots per wave (row tiles ri = (w * RB + s) * R + y) and column x's N slice of every op. +// EMBED : x = patches @ Wpe + b (patch slots) | prefix constants (prefix slots) +// STATS : producer: per-slot row sums of x / x^2 over the slice -> one packed fp32 tile (columns 2s, 2s + 1); +// consumer: mu / E2 = sum of the row's C tiles @ SEL (x 1/D), rstd, std, EXT = [-mu | std] (bf16) +// QKV : per head unit: rstd (x @ W' + EXT @ [c ; bias']) -> RoPE (q / k of patch slots) -> bf16 -> staging +// ATT : items (head, q block): online softmax over key chunks, O / l -> bf16 -> staging +// PROJ : x += attn @ Wp' + E0 @ [b'] (LayerScale folded), fp32 residual +// FC1 : GELU(rstd (x @ W1' + EXT @ [c ; bias'])) | SiLU(g) u (SwiGLU) -> bf16 (row gather) +// FC2 : x += h @ W2' + E0 @ [b'] +// Matmuls: bf16 weights, HiFi4 (ME_FID overrides), fp32 DST accumulation (full sync: 8 tiles); residual, statistics, +// softmax in fp32. A released DST reads as 0 for the FPU; every SFPU operand is written in the current section. +#include +#define REDUCE_OP (PoolType::MAX) +#define REDUCE_DIM (ReduceDim::REDUCE_ROW) +#include "api/compute/compute_kernel_api.h" +#include "api/compute/eltwise_binary.h" +#include "api/compute/eltwise_binary_sfpu.h" +#include "api/compute/binary_max_min.h" +#include "api/compute/bcast.h" +#include "api/compute/matmul.h" +#include "api/compute/reduce.h" +#include "api/compute/tile_move_copy.h" +#include "api/compute/eltwise_unary/exp.h" +#include "api/compute/eltwise_unary/gelu.h" +#include "api/compute/eltwise_unary/recip.h" +#include "api/compute/eltwise_unary/rsqrt.h" +#include "api/compute/eltwise_unary/sqrt.h" +#include "api/compute/eltwise_unary/binop_with_scalar.h" +#include "api/compute/reconfig_data_format.h" +#include "api/compute/compute_kernel_hw_startup.h" +#include "me_sched.hpp" +#if defined(TRISC_MATH) || defined(TRISC_PACK) +#include "llk_math_eltwise_binary_sfpu_macros.h" +#include "me_sfpu.hpp" +#endif + +#define NOINL __attribute__((noinline, noclone)) + +using namespace mex; + +namespace { + +#ifdef ME_FID +constexpr MathFidelity FID = static_cast(ME_FID); +#else +constexpr MathFidelity FID = MathFidelity::HiFi4; +#endif + +// ---------------------------------------------------------------- LLK wrappers +ALWI void mm_init_f(uint32_t in0, uint32_t in1, uint32_t transpose = 0) { + reconfig_data_format(in1, in0); // matmul: SrcA <- in1, SrcB <- in0 + MATH((llk_math_matmul_init(in0, in1, transpose))); + UNPACK((llk_unpack_AB_matmul_init(in0, in1, transpose))); +} +ALWI void mm_f(uint32_t in0, uint32_t in1, uint32_t t0, uint32_t t1, uint32_t dst) { + UNPACK((llk_unpack_AB_matmul(in0, in1, t0, t1))); + MATH((llk_math_matmul(dst))); +} +// out-of-line matmul helpers (the kernel-config buffer holds every binary: code size matters; the hot matmul loops of +// mm_slots / PV keep the inline mm_f) +NOINL void mm_init_n(uint32_t in0, uint32_t in1, uint32_t transpose) { mm_init_f(in0, in1, transpose); } +NOINL void mm_n(uint32_t in0, uint32_t in1, uint32_t t0, uint32_t t1, uint32_t dst) { mm_f(in0, in1, t0, t1, dst); } +NOINL void load(uint32_t cb, uint32_t tile, uint32_t dst) { + reconfig_data_format_srca(cb); + copy_init(cb); + copy_tile(cb, tile, dst); +} +NOINL void fmul(uint32_t a, uint32_t b, uint32_t o) { + mul_binary_tile_init(); + mul_binary_tile(a, b, o); +} +NOINL void fadd(uint32_t a, uint32_t b, uint32_t o) { + add_binary_tile_init(); + add_binary_tile(a, b, o); +} +NOINL void fsub(uint32_t a, uint32_t b, uint32_t o) { + sub_binary_tile_init(); + sub_binary_tile(a, b, o); +} +NOINL void fmax(uint32_t a, uint32_t b, uint32_t o) { + binary_max_tile_init(); + binary_max_tile(a, b, o); +} +NOINL void faddc(uint32_t a, uint32_t bits) { + binop_with_scalar_tile_init(); + add_unary_tile(a, bits); +} +NOINL void fmulc(uint32_t a, uint32_t bits) { + binop_with_scalar_tile_init(); + mul_unary_tile(a, bits); +} +NOINL void frsqrt(uint32_t a) { + rsqrt_tile_init(); + rsqrt_tile(a); +} +NOINL void fsqrt(uint32_t a) { + sqrt_tile_init(); + sqrt_tile(a); +} +NOINL void frecip(uint32_t a) { + recip_tile_init(); + recip_tile(a); +} +NOINL void fexp(uint32_t a) { + exp_tile_init(); + exp_tile(a); +} +// the softmax exp: ME_EXP 0 fp32-accurate, 1 exp_21f (15 instructions, bf16-accurate: max rel err 1.7e-3) +NOINL void fexp_p(uint32_t a) { +#if ME_EXP == 1 + exp_tile_init(); + exp_tile(a); +#else + exp_tile_init(); + exp_tile(a); +#endif +} +// dst[a] = GELU(dst[a] * dst[r]): ME_GELU 1 polynomial (MoGe-2 v5, max |err| 2.1e-4), 0 exact erf GELU +NOINL void frgelu(uint32_t a, uint32_t r) { +#if ME_GELU == 1 + MATH((::ckernel::llk_math_eltwise_unary_sfpu_init(::ckernel::sfpu::me_gelu_init))); + MATH(SFPU_BINARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, me_rgelu, a, r, a, VectorMode::RC)); +#else + fmul(a, r, a); + gelu_tile_init(); + gelu_tile(a); +#endif +} +NOINL void frswiglu(uint32_t g, uint32_t u, uint32_t r) { + silu_tile_init(); + MATH(SFPU_BINARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, me_rswiglu, g, u, r, VectorMode::RC)); +} +NOINL void fsplit(uint32_t a, uint32_t lo) { + mul_binary_tile_init(); + MATH(SFPU_BINARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, me_split, a, lo, 0, VectorMode::RC)); +} +NOINL void frope(uint32_t a, uint32_t r) { + mul_binary_tile_init(); + MATH(SFPU_BINARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, me_rope, a, r, 0, VectorMode::RC)); +} +NOINL void frscale2(uint32_t a, uint32_t r) { + mul_binary_tile_init(); + MATH(SFPU_BINARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, me_rscale2, a, r, 0, VectorMode::RC)); +} +NOINL void fgelu(uint32_t a) { + gelu_tile_init(); + gelu_tile(a); +} +NOINL void fsilu(uint32_t a) { + silu_tile_init(); + silu_tile(a); +} +NOINL void pack_to(uint32_t dst, uint32_t cb, uint32_t idx) { + pack_reconfig_data_format(cb); + pack_tile(dst, cb, idx); +} + +// weight stream: tiles are consumed in pages of PAGE_TILES (each wave's arena column is padded to whole pages) +struct WS { + uint32_t t = 0; + uint32_t used = 0; // tiles consumed in the current arena + ALWI uint32_t next() { + if (t == 0) { + cb_wait_front(CB_W, PAGE_TILES); + } + return t; + } + ALWI void done() { + ++used; + if (++t == PAGE_TILES) { + cb_pop_front(CB_W, PAGE_TILES); + t = 0; + } + } + // n tiles (a power of two <= 8, starting n-aligned: never across a page) + ALWI void done_n(uint32_t n) { + used += n; + t += n; + if (t == PAGE_TILES) { + cb_pop_front(CB_W, PAGE_TILES); + t = 0; + } + } +}; +WS ws; + +// the largest power of two <= min(gmax, n) (geometry.pow2_groups) +ALWI uint32_t pow2_floor(uint32_t n, uint32_t gmax) { + uint32_t g = 1; + while (g * 2 <= n && g * 2 <= gmax) { + g *= 2; + } + return g; +} + +NOINL void skip_w(uint32_t n) { + for (uint32_t i = 0; i < n; ++i) { + ws.next(); + ws.done(); + } +} +// end of an op segment: skip to the next page boundary (each op segment is page-padded) +NOINL void ws_align() { + if (ws.t != 0) { + skip_w(PAGE_TILES - ws.t); + } +} +// end of a wave's arena: skip the tiles not consumed (pad, or ops not run in a debug run) +NOINL void arena_end(uint32_t pages) { + skip_w(pages * PAGE_TILES - ws.used); + ws.used = 0; +} + +// DST[s * nj + j] += sum_k in0[k * RB + s] @ W_k,j for every slot (block matmul: rt = RB slots, ct = nj, one unpack of +// the RB in0 tiles and the nj weight tiles per k); weights k-major, nj (a power of two) per k inside one page. +// Inactive slots compute garbage the callers discard (residual ops reload their x). +NOINL void mm_block_init(uint32_t in0, uint32_t in1, uint32_t ct, uint32_t rt) { + reconfig_data_format(in1, in0); // matmul: SrcA <- in1, SrcB <- in0 + MATH((llk_math_matmul_init(in0, in1, 0, ct, rt))); + UNPACK((llk_unpack_AB_matmul_init(in0, in1, 0, ct, rt, 1))); +} +#ifdef ME_MM_BLOCK +NOINL void mm_slots(uint32_t in0, uint32_t K, uint32_t nj, uint32_t /*act*/) { + mm_block_init(in0, CB_W, nj, RB); + for (uint32_t k = 0; k < K; ++k) { + const uint32_t w = ws.next(); + UNPACK((llk_unpack_AB_matmul(in0, CB_W, k * RB, w, nj, RB, 1))); + MATH((llk_math_matmul(0, nj, RB))); + ws.done_n(nj); + } +} +#else +// per-tile matmuls (measured faster than the LLK block matmul for these 2 x 2 .. 2 x 4 blocks: FC2 66 vs 109 +// cycles per tile; HiFi4 peak is 64) +NOINL void mm_slots(uint32_t in0, uint32_t K, uint32_t nj, uint32_t /*act*/) { + mm_block_init(in0, CB_W, 1, 1); + for (uint32_t k = 0; k < K; ++k) { + const uint32_t w = ws.next(); + for (uint32_t j = 0; j < nj; ++j) { + for (uint32_t s = 0; s < RB; ++s) { + UNPACK((llk_unpack_AB_matmul(in0, CB_W, k * RB + s, w + j))); + MATH((llk_math_matmul(s * nj + j))); + } + } + ws.done_n(nj); + } +} +#endif +// the extra K tile: DST[s * nj + j] += in0[tb + s * ts] @ X_j (ts = 0: one shared in0 tile; ts = 1: RB tiles) +NOINL void mm_extra(uint32_t in0, uint32_t tb, uint32_t ts, uint32_t nj, uint32_t /*act*/) { + if (ts == 1) { + mm_block_init(in0, CB_W, nj, RB); + const uint32_t w = ws.next(); + UNPACK((llk_unpack_AB_matmul(in0, CB_W, tb, w, nj, RB, 1))); + MATH((llk_math_matmul(0, nj, RB))); + ws.done_n(nj); + return; + } + mm_block_init(in0, CB_W, nj, 1); + const uint32_t w = ws.next(); + for (uint32_t s = 0; s < RB; ++s) { + UNPACK((llk_unpack_AB_matmul(in0, CB_W, tb, w, nj, 1, 1))); + MATH((llk_math_matmul(s * nj, nj, 1))); + } + ws.done_n(nj); +} + +#if ME_PROF +ALWI volatile uint32_t* tprof_ptr() { + const auto& iface = get_local_cb_interface(CB_SYNC); + return reinterpret_cast(((iface.fifo_limit - iface.fifo_size) << 4) + SYNC_PROF); +} +#define TPROF(i) UNPACK((tprof_ptr()[(i)] = get_timestamp_32b())) +#define TPROFP(i) PACK((tprof_ptr()[(i)] = get_timestamp_32b())) +#else +#define TPROF(i) +#define TPROFP(i) +#endif +bool wprof = false; // detail stamps of block 1, wave 0 +#define WPROF(i) TPROF(wprof ? 256 + (i) : 511) +#define WPROFP(i) TPROFP(wprof ? 256 + (i) : 511) +bool aprof = false; // detail stamps of the first (q tile, chunk) of block 1's first item +#define APROF(i) TPROF(aprof ? 384 + (i) : 511) +#define APROFP(i) TPROFP(aprof ? 384 + (i) : 511) + +// ---------------------------------------------------------------- debug probes (ME_PROBE) +uint32_t n_probe = N_PROBE; // probes left to take (armed by setting it to 0) +NOINL void probe(uint32_t cb, uint32_t tile) { +#if ME_PROBE + if (n_probe >= N_PROBE) { + return; + } + ++n_probe; + cb_reserve_back(CB_PRB, 1); + tile_regs_acquire(); + load(cb, tile, 0); + tile_regs_commit(); + tile_regs_wait(); + pack_to(0, CB_PRB, 0); + tile_regs_release(); + cb_push_back(CB_PRB, 1); +#endif +} +NOINL void probe_fill() { + while (n_probe < N_PROBE) { + probe(CB_CF32, F_ZERO); + } +} + +struct Me { + uint32_t x, y, h0, nh, n0, nx, f0, nf, eps, nl, dump, npe, npb, npbl, inv_d, inv_t; + uint32_t kd[RB]; +}; +Me me; + +ALWI uint32_t gmin(uint32_t a, uint32_t b) { return a < b ? a : b; } + +void kinds(uint32_t w) { + for (uint32_t s = 0; s < RB; ++s) { + me.kd[s] = kind_of(ri_of(w, me.y, s)); + } +} +uint32_t mlp_mask(uint32_t l) { + uint32_t m = 0; + for (uint32_t s = 0; s < RB; ++s) { + m |= mlp_on(l, me.kd[s]) ? (1u << s) : 0u; + } + return m; +} + +// ================================================================ residual x (CB_X: front = current x, s * NXM + j) +// x load (NW > 1): XL -> X (slots without a stored x stay 0) +NOINL void x_from_xl() { + cb_wait_front(CB_XL, RB * NXM); + cb_reserve_back(CB_X, RB * NXM); + for (uint32_t s = 0; s < RB; ++s) { + tile_regs_acquire(); + const bool ld = me.kd[s] == KD_PREFIX || me.kd[s] == KD_PATCH; + for (uint32_t j = 0; j < me.nx; ++j) { + load(ld ? CB_XL : CB_CF32, ld ? s * NXM + j : F_ZERO, j); + } + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_X); + for (uint32_t j = 0; j < me.nx; ++j) { + pack_tile(j, CB_X, s * NXM + j); + } + tile_regs_release(); + } + cb_push_back(CB_X, RB * NXM); + cb_pop_front(CB_XL, RB * NXM); +} + +// x of slot s -> CB_XO (fp32, BRISC stores it to XD) +NOINL void x_out(uint32_t s) { + cb_reserve_back(CB_XO, NXM); + tile_regs_acquire(); + for (uint32_t j = 0; j < me.nx; ++j) { + load(CB_X, s * NXM + j, j); + } + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_XO); + for (uint32_t j = 0; j < me.nx; ++j) { + pack_tile(j, CB_XO, j); + } + tile_regs_release(); + cb_push_back(CB_XO, NXM); +} + +// ================================================================ statistics +// producer: per-slot row sums of x / x^2 over the slice -> one packed fp32 tile STO (columns 2s, 2s + 1 = hi, +// 8 + 2s, 8 + 2s + 1 = lo: fp32-accurate through the consumer's tf32 matmuls); bf16(x) -> OUTX (j * RB + s) +NOINL void stats_out() { + const uint32_t nx = me.nx; + cb_wait_front(CB_X, RB * NXM); + cb_reserve_back(CB_SUMS, 4 * RB); + for (uint32_t s = 0; s < RB; ++s) { + tile_regs_acquire(); + for (uint32_t j = 0; j < nx; ++j) { + load(CB_X, s * NXM + j, j); + } + // S at 4, Q at 5, square temp 6 (every SFPU operand written in this section) + load(CB_X, s * NXM, 4); + fmul(0, 0, 5); + for (uint32_t j = 1; j < nx; ++j) { + fadd(4, j, 4); + fmul(j, j, 6); + fadd(5, 6, 5); + } + fsplit(4, 6); + fsplit(5, 7); + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_SUMS); + pack_tile(4, CB_SUMS, 4 * s); + pack_tile(6, CB_SUMS, 4 * s + 1); + pack_tile(5, CB_SUMS, 4 * s + 2); + pack_tile(7, CB_SUMS, 4 * s + 3); + tile_regs_release(); + } + cb_push_back(CB_SUMS, 4 * RB); + // row sums (fp32 DST) -> hi / lo -> SUMS[0, 1] of the next cycle + cb_wait_front(CB_SUMS, 4 * RB); + tile_regs_acquire(); + mm_init_n(CB_SUMS, CB_CONST, 0); + for (uint32_t s = 0; s < RB; ++s) { + mm_n(CB_SUMS, CB_CONST, 4 * s, C_L0 + 2 * s, 0); + mm_n(CB_SUMS, CB_CONST, 4 * s + 1, C_L0 + 2 * s, 0); + mm_n(CB_SUMS, CB_CONST, 4 * s + 2, C_L0 + 2 * s + 1, 0); + mm_n(CB_SUMS, CB_CONST, 4 * s + 3, C_L0 + 2 * s + 1, 0); + } + fsplit(0, 1); + tile_regs_commit(); + cb_pop_front(CB_SUMS, 4 * RB); + cb_reserve_back(CB_SUMS, 4 * RB); + tile_regs_wait(); + pack_reconfig_data_format(CB_SUMS); + pack_tile(0, CB_SUMS, 0); + pack_tile(1, CB_SUMS, 1); + tile_regs_release(); + cb_push_back(CB_SUMS, 4 * RB); + cb_wait_front(CB_SUMS, 4 * RB); + cb_reserve_back(CB_STO, 1); + tile_regs_acquire(); + mm_init_n(CB_SUMS, CB_CONST, 0); + mm_n(CB_SUMS, CB_CONST, 0, C_I, 0); + mm_n(CB_SUMS, CB_CONST, 1, C_SH8, 0); + tile_regs_commit(); + tile_regs_wait(); + pack_to(0, CB_STO, 0); + tile_regs_release(); + cb_push_back(CB_STO, 1); + cb_pop_front(CB_SUMS, 4 * RB); + // bf16(x) slice, k-major + cb_reserve_back(CB_OUTX, NXM * RB); + for (uint32_t s = 0; s < RB; ++s) { + tile_regs_acquire(); + for (uint32_t j = 0; j < nx; ++j) { + load(CB_X, s * NXM + j, j); + } + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_OUTX); + for (uint32_t j = 0; j < nx; ++j) { + pack_tile(j, CB_OUTX, j * RB + s); + } + tile_regs_release(); + } + cb_push_back(CB_OUTX, NXM * RB); +} + +// consumer: mu / rstd / std of every slot at once (columns s of one tile each, fp32 SFPU), then per slot +// EXT = [-mu | std] (bf16) and rstd broadcast over the columns (fp32) by selector matmuls +NOINL void stats_in() { + cb_wait_front(CB_STAT, C); + cb_reserve_back(CB_SC, 6); + tile_regs_acquire(); + mm_init_n(CB_STAT, CB_CONST, 0); + for (uint32_t c = 0; c < C; ++c) { + mm_n(CB_STAT, CB_CONST, c, C_PA, 0); + } + for (uint32_t c = 0; c < C; ++c) { + mm_n(CB_STAT, CB_CONST, c, C_PB, 1); + } + fmulc(0, me.inv_d); // mu + fmulc(1, me.inv_d); // E[x^2] + fmul(0, 0, 4); // mu^2 + fsub(1, 4, 2); + faddc(2, me.eps); // var + eps + fsub(1, 4, 3); + faddc(3, me.eps); + frsqrt(2); // rstd + fsqrt(3); // std + fsplit(0, 1); // mu hi (0) / lo (1) + fsplit(2, 5); // rstd hi (2) / lo (5): its broadcast below stays fp32-accurate + fsplit(3, 6); // std hi (3) / lo (6) + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_SC); + pack_tile(0, CB_SC, 0); + pack_tile(1, CB_SC, 1); + pack_tile(2, CB_SC, 2); + pack_tile(5, CB_SC, 3); + pack_tile(3, CB_SC, 4); + pack_tile(6, CB_SC, 5); + tile_regs_release(); + cb_push_back(CB_SC, 6); + cb_pop_front(CB_STAT, C); + cb_wait_front(CB_SC, 6); + cb_reserve_back(CB_EXT, RB); + cb_reserve_back(CB_RSTD, RB); + tile_regs_acquire(); + mm_init_n(CB_SC, CB_CONST, 0); + for (uint32_t s = 0; s < RB; ++s) { // EXT = [-mu hi, -mu lo, std hi, std lo, -mu hi, std hi] (arena._ext) + mm_n(CB_SC, CB_CONST, 0, C_PM0 + s, s); + mm_n(CB_SC, CB_CONST, 1, C_PM1 + s, s); + mm_n(CB_SC, CB_CONST, 4, C_PS0 + s, s); + mm_n(CB_SC, CB_CONST, 5, C_PS1 + s, s); + } + for (uint32_t s = 0; s < RB; ++s) { + mm_n(CB_SC, CB_CONST, 2, C_SEL0 + s, 4 + s); + mm_n(CB_SC, CB_CONST, 3, C_SEL0 + s, 4 + s); + } + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_EXT); + for (uint32_t s = 0; s < RB; ++s) { + pack_tile(s, CB_EXT, s); + } + pack_reconfig_data_format(CB_RSTD); + for (uint32_t s = 0; s < RB; ++s) { + pack_tile(4 + s, CB_RSTD, s); + } + tile_regs_release(); + cb_push_back(CB_EXT, RB); + cb_push_back(CB_RSTD, RB); + cb_pop_front(CB_SC, 6); + cb_wait_front(CB_EXT, RB); + cb_wait_front(CB_RSTD, RB); +} +NOINL void stats_pop() { + cb_pop_front(CB_EXT, RB); + cb_pop_front(CB_RSTD, RB); +} + +// ================================================================ residual matmul ops (embed / proj / fc2) +// mode 0: embed (in0 = patches, K = PE_T; prefix slots copy PFX), 1: proj (in0 = attention output, K = DT), +// 2: fc2 (in0 = FC1 output, K = FT). x_new = x_old (or 0 / PFX) + in0 @ W + E0 @ [b] for the active slots. +NOINL void residual_op(uint32_t mode, uint32_t act) { + const uint32_t K = mode == 0 ? PE_T : mode == 1 ? DT : FT; + cb_wait_front(CB_INF, INF_CAP); + WPROF(mode == 1 ? 8 : 9); + if (mode != 0) { + cb_wait_front(CB_X, RB * NXM); + } + cb_reserve_back(CB_X, RB * NXM); + for (uint32_t g0 = 0; g0 < me.nx;) { + const uint32_t nj = pow2_floor(me.nx - g0, G); + tile_regs_acquire(); + if (mode != 0) { // every accumulator starts from x (fp32 unpack to DST) + for (uint32_t s = 0; s < RB; ++s) { + for (uint32_t j = 0; j < nj; ++j) { + load(CB_X, s * NXM + g0 + j, s * nj + j); + } + } + } + mm_slots(CB_INF, K, nj, act); + mm_extra(CB_CONST, C_E0, 0, nj, act); + // after the matmuls: inactive slots get their x back (frozen prefix) / prefix constants / zeros (embed). + // An fp32 unpack-to-DST into tile i >= 4 clears the DST zero flags of tile i & 3 (tt-llk budabackend#2730 + // workaround, 4 fp32 tiles per bank): never before an FPU accumulation into a fresh tile (MK_LOG round 2). + for (uint32_t s = 0; s < RB; ++s) { + if (act & (1u << s)) { + continue; + } + for (uint32_t j = 0; j < nj; ++j) { + if (mode != 0) { + load(CB_X, s * NXM + g0 + j, s * nj + j); + } else if (me.kd[s] == KD_PREFIX) { + load(CB_PFX, g0 + j, s * nj + j); + } else { + load(CB_CF32, F_ZERO, s * nj + j); + } + } + } + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_X); + for (uint32_t s = 0; s < RB; ++s) { + for (uint32_t j = 0; j < nj; ++j) { + // the new x sits after the old one in the FIFO: pack_tile indexes from the write pointer + pack_tile(s * nj + j, CB_X, s * NXM + g0 + j); + } + } + tile_regs_release(); + g0 += nj; + } + ws_align(); + if (mode != 0) { + cb_pop_front(CB_X, RB * NXM); + } + cb_push_back(CB_X, RB * NXM); + cb_pop_front(CB_INF, INF_CAP); +} + +// ================================================================ QKV(l) +NOINL void qkv(uint32_t l) { + cb_wait_front(CB_INX, INX_CAP); + WPROF(10); + stats_in(); + WPROFP(11); + cb_wait_front(CB_TAB, 2 * RB); + for (uint32_t jh = 0; jh < me.nh; ++jh) { + const uint32_t u = me.h0 + jh, ty = unit_type(u); + uint32_t act = 0; + for (uint32_t s = 0; s < RB; ++s) { + act |= ((qkv_mask(l, me.kd[s]) >> ty) & 1u) << s; + } + if constexpr (RB <= 2) { // epilogue in DST: accumulators 0 .. 3, rstd / cos / sin of a slot at 4 / 5 / 6 + tile_regs_acquire(); + mm_slots(CB_INX, DT, 2, act); + mm_extra(CB_EXT, 0, 1, 2, act); + for (uint32_t s = 0; s < RB; ++s) { + if (!(act & (1u << s))) { + continue; + } + load(CB_RSTD, s, 4); + if (ty < 2 && me.kd[s] == KD_PATCH) { + load(CB_TAB, 2 * s, 5); + load(CB_TAB, 2 * s + 1, 6); + frope(2 * s, 4); + } else { + frscale2(2 * s, 4); + } + } + tile_regs_commit(); + cb_reserve_back(CB_OUT, 2 * RB); + tile_regs_wait(); + pack_reconfig_data_format(CB_OUT); + for (uint32_t i = 0; i < 2 * RB; ++i) { + pack_tile(i, CB_OUT, i); + } + tile_regs_release(); + cb_push_back(CB_OUT, 2 * RB); + continue; + } + tile_regs_acquire(); + mm_slots(CB_INX, DT, 2, act); + mm_extra(CB_EXT, 0, 1, 2, act); + tile_regs_commit(); + cb_reserve_back(CB_RAW, 8); + tile_regs_wait(); + pack_reconfig_data_format(CB_RAW); + for (uint32_t i = 0; i < 2 * RB; ++i) { + pack_tile(i, CB_RAW, i); + } + tile_regs_release(); + cb_push_back(CB_RAW, 8); + cb_wait_front(CB_RAW, 8); + cb_reserve_back(CB_OUT, 2 * RB); + for (uint32_t s = 0; s < RB; ++s) { + if (!(act & (1u << s))) { + continue; + } + tile_regs_acquire(); + load(CB_RAW, 2 * s, 0); + load(CB_RAW, 2 * s + 1, 1); + load(CB_RSTD, s, 4); + if (ty < 2 && me.kd[s] == KD_PATCH) { + load(CB_TAB, 2 * s, 5); + load(CB_TAB, 2 * s + 1, 6); + frope(0, 4); + } else { + frscale2(0, 4); + } + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_OUT); + pack_tile(0, CB_OUT, 2 * s); + pack_tile(1, CB_OUT, 2 * s + 1); + tile_regs_release(); + } + cb_push_back(CB_OUT, 2 * RB); + cb_pop_front(CB_RAW, 8); + } + ws_align(); + cb_pop_front(CB_INX, INX_CAP); + stats_pop(); +} + +// ================================================================ FC1(l), pipelined (ME_FC1P: rb == 2, GELU) +// mk_vision's MV_FC1P (VLA-JEPA, MK_LOG 3.10): for this phase both threads switch the DST to half-sync (two halves +// of 4 fp32 tiles), so the math thread's matmuls into one half overlap the pack thread's SFPU epilogue (rstd x GELU) +// + pack of the other. Half layout: 0, 1 = the f tile's two slot accumulators, 2, 3 = the slots' rstd, loaded once +// per half (first two sections). A section is released without the half-wide ZEROACC: the pack thread clears only +// the accumulators (an FPU accumulation onto rows the SFPU wrote is wrong), so the operand tiles survive. h_end +// returns to full sync and closes with one empty standard section, whose release clears the whole DST. +#if ME_FC1P +NOINL void h_begin() { + MATH((_llk_math_pack_sync_init_())); + PACK((_llk_pack_dest_init_())); +} +NOINL void h_end() { + MATH((_llk_math_pack_sync_init_())); + PACK((_llk_pack_dest_init_())); + tile_regs_acquire(); + tile_regs_commit(); + tile_regs_wait(); + tile_regs_release(); +} +ALWI void h_acquire() { MATH((_llk_math_wait_for_dest_available_())); } +ALWI void h_commit() { MATH((_llk_math_dest_section_done_())); } +ALWI void h_wait() { + PACK(TTI_SEMWAIT(p_stall::STALL_TDMA | p_stall::STALL_SYNC | p_stall::STALL_SFPU, + ckernel::semaphore::t6_sem(ckernel::semaphore::MATH_PACK), p_stall::STALL_ON_ZERO)); +} +NOINL void h_release() { + PACK(({ + TTI_STALLWAIT(p_stall::STALL_MATH | p_stall::STALL_SFPU | p_stall::STALL_SYNC, p_stall::PACK | p_stall::WAIT_SFPU); + ckernel::math::set_dst_write_addr(0); + for (uint32_t i = 0; i < 8; ++i) { + TT_ZEROACC(p_zeroacc::CLR_16, 1, 0, ADDR_MOD_7, i); + } + TTI_STALLWAIT(p_stall::STALL_SYNC, p_stall::MATH); + _llk_pack_dest_section_done_(); + })); +} + +NOINL void fc1(uint32_t /*act*/) { + static_assert(RB == 2 && !SWIGLU, "pipelined FC1"); + cb_wait_front(CB_INX, INX_CAP); + WPROF(6); + stats_in(); + WPROFP(7); + h_begin(); + PACK((::ckernel::llk_math_eltwise_unary_sfpu_init(::ckernel::sfpu::me_gelu_init))); + pack_reconfig_data_format(CB_FO); + for (uint32_t t = 0; t < me.nf; ++t) { + const uint32_t slot = t % FB; + h_acquire(); + if (t < 2) { // the operand tiles of this half + load(CB_RSTD, 0, 2); + load(CB_RSTD, 1, 3); + mm_init_n(CB_INX, CB_W, 0); + } + for (uint32_t k = 0; k < DT; ++k) { + const uint32_t w = ws.next(); + mm_f(CB_INX, CB_W, 2 * k, w, 0); + mm_f(CB_INX, CB_W, 2 * k + 1, w, 1); + ws.done(); + } + { // the extra K tile [-mu | std] @ [c ; bias'] (CB_EXT: same tile format as CB_INX, no re-init) + const uint32_t w = ws.next(); + mm_f(CB_EXT, CB_W, 0, w, 0); + mm_f(CB_EXT, CB_W, 1, w, 1); + ws.done(); + } + h_commit(); + if (slot == 0) { + cb_reserve_back(CB_FO, FB * RB); + } + h_wait(); + PACK(SFPU_BINARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, me_rgelu, 0, 2, 0, VectorMode::RC)); + PACK(SFPU_BINARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, me_rgelu, 1, 3, 1, VectorMode::RC)); + PACK(TTI_STALLWAIT(p_stall::STALL_PACK, p_stall::WAIT_SFPU)); + pack_tile(0, CB_FO, slot * RB); + pack_tile(1, CB_FO, slot * RB + 1); + h_release(); + if (slot + 1 == FB || t + 1 == me.nf) { + cb_push_back(CB_FO, FB * RB); + } + } + h_end(); + ws_align(); + cb_pop_front(CB_INX, INX_CAP); + stats_pop(); +} +#else +// ================================================================ FC1(l) +NOINL void fc1(uint32_t act) { + constexpr uint32_t TW = SWIGLU ? 2 : 1; // weight tiles per hidden tile + cb_wait_front(CB_INX, INX_CAP); + WPROF(6); + stats_in(); + WPROFP(7); + // epilogue in DST: accumulators s * nt + t (rb * nt <= 4), rstd of slot s at 4 + s (loaded after the matmuls) + for (uint32_t fb = 0; fb < me.nf;) { + const uint32_t nb = pow2_floor(me.nf - fb, FB), nt = nb * TW; + tile_regs_acquire(); + mm_slots(CB_INX, DT, nt, act); + mm_extra(CB_EXT, 0, 1, nt, act); + for (uint32_t s = 0; s < RB; ++s) { + if (!(act & (1u << s))) { + continue; + } + load(CB_RSTD, s, 4 + s); + for (uint32_t jj = 0; jj < nb; ++jj) { + if (SWIGLU) { + frswiglu(s * nt + 2 * jj, s * nt + 2 * jj + 1, 4 + s); + } else { + frgelu(s * nt + jj, 4 + s); + } + } + } + tile_regs_commit(); + cb_reserve_back(CB_FO, FB * RB); + tile_regs_wait(); + pack_reconfig_data_format(CB_FO); + for (uint32_t s = 0; s < RB; ++s) { + for (uint32_t jj = 0; jj < nb; ++jj) { + pack_tile(s * nt + (SWIGLU ? 2 * jj : jj), CB_FO, jj * RB + s); + } + } + tile_regs_release(); + cb_push_back(CB_FO, FB * RB); + fb += nb; + } + ws_align(); + cb_pop_front(CB_INX, INX_CAP); + stats_pop(); +} + +#endif // ME_FC1P + +// ================================================================ tap / pool +NOINL void tap_out() { + for (uint32_t s = 0; s < RB; ++s) { + if (!tap_on(me.kd[s])) { + continue; + } + cb_reserve_back(CB_TAP, NXM); + tile_regs_acquire(); + for (uint32_t j = 0; j < me.nx; ++j) { + load(CB_X, s * NXM + j, j); + } + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_TAP); + for (uint32_t j = 0; j < me.nx; ++j) { + pack_tile(j, CB_TAP, j); + } + tile_regs_release(); + cb_push_back(CB_TAP, NXM); + } +} + +// a sync word written by the BRISC before it pushed CB_CONST: the unpack thread (which waited on CB_CONST) reads it +// and hands it to the math / pack threads through the mailboxes (cb_api.h read_tile_value), so all three agree +NOINL uint32_t sync_value(uint32_t w) { + uint32_t v = 0; + UNPACK({ + asm volatile("fence" ::: "memory"); + const auto& iface = get_local_cb_interface(CB_SYNC); + v = reinterpret_cast(((iface.fifo_limit - iface.fifo_size) << 4) + w * SYNC_STRIDE)[0]; + ckernel::mailbox_write(ckernel::ThreadId::MathThreadId, v); + ckernel::mailbox_write(ckernel::ThreadId::PackThreadId, v); + }) + MATH(v = ckernel::mailbox_read(ckernel::ThreadId::UnpackThreadId);) + PACK(v = ckernel::mailbox_read(ckernel::ThreadId::UnpackThreadId);) + return v; +} + +// before LN1 of a joint block: prefix slots ship their x (XD), the pool slot's x = mean over frames < n of those +NOINL void pool() { + bool own = false; + for (uint32_t s = 0; s < RB; ++s) { + if (me.kd[s] == KD_PREFIX) { + x_out(s); + } + own = own || me.kd[s] == KD_POOL; + } + if (!own) { + return; + } + cb_wait_front(CB_X, RB * NXM); + cb_reserve_back(CB_X, RB * NXM); + for (uint32_t s = 0; s < RB; ++s) { + tile_regs_acquire(); + if (me.kd[s] == KD_POOL) { + for (uint32_t t = 0; t < g_nv; ++t) { + cb_wait_front(CB_PL, NXM); + for (uint32_t j = 0; j < me.nx; ++j) { + if (t == 0) { + load(CB_PL, j, j); + } else { + load(CB_PL, j, 4 + j); + fadd(j, 4 + j, j); + } + } + cb_pop_front(CB_PL, NXM); + } + for (uint32_t j = 0; j < me.nx; ++j) { + fmulc(j, me.inv_t); + } + } else { + for (uint32_t j = 0; j < me.nx; ++j) { + load(CB_X, s * NXM + j, j); + } + } + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_X); + for (uint32_t j = 0; j < me.nx; ++j) { + pack_tile(j, CB_X, s * NXM + j); + } + tile_regs_release(); + } + cb_pop_front(CB_X, RB * NXM); + cb_push_back(CB_X, RB * NXM); +} + +// ================================================================ attention item +constexpr uint32_t SUB = 6; // score tiles per DST section (DST 0 .. 5; 6 = the shift, 7 = a mask temp) +// DST jj = q_i @ K_{j0 + jj}^T (+ mask), jj < n +NOINL void scores(uint32_t i, uint32_t j0, uint32_t n, const uint32_t* mk) { + mm_init_n(CB_AQ, CB_KV, 1); + for (uint32_t jj = 0; jj < n; ++jj) { + for (uint32_t d = 0; d < 2; ++d) { + mm_n(CB_AQ, CB_KV, 2 * i + d, 2 * (j0 + jj) + d, jj); + } + } + for (uint32_t jj = 0; jj < n; ++jj) { + if (mk[j0 + jj]) { + load(CB_CF32, mk[j0 + jj] == 1 ? F_MASKP : F_MASKN, 7); + fadd(jj, 7, jj); + } + } +} + +// the score region (S32 / S32F / AP views, KC fp32 tiles): every view pushes / pops exactly KC tiles per use +ALWI void region_push(uint32_t cb) { + cb_push_back(cb, KC); +} +// row max of the nk fp32 tiles of the score region (FPU reduce; tf32 operand: rel err 2^-11) -> CB_MX +NOINL void rowmax(uint32_t nk) { + cb_wait_front(CB_S32F, KC); + cb_reserve_back(CB_MX, 1); + tile_regs_acquire(); + reconfig_data_format(CB_S32F, CB_CONST); + reduce_init(CB_S32F, CB_CONST, CB_MX); + for (uint32_t j = 0; j < nk; ++j) { + reduce_tile(CB_S32F, CB_CONST, j, C_ONES, 0); + } + tile_regs_commit(); + tile_regs_wait(); + pack_to(0, CB_MX, 0); + tile_regs_release(); + reduce_uninit(CB_S32F); + cb_push_back(CB_MX, 1); + cb_pop_front(CB_S32F, KC); + cb_wait_front(CB_MX, 1); +} +// DST dst = the CB_MX column vector broadcast over the columns +NOINL void bcast_m(uint32_t dst) { + reconfig_data_format(CB_CONST, CB_MX); + mul_bcast_cols_init(CB_CONST, CB_MX); + mul_tiles_bcast_cols(CB_CONST, CB_MX, C_ONES, 0, dst); +} +// dst[0 .. n) = exp(dst[0 .. n) - dst[m]): ME_EXP 1 fused sfpi exp_21f, 0 fused fp32-accurate exp, 2 the max +// subtraction then the stock TTI exp_21f per tile (result rounded to bf16 precision) +NOINL void fsubexp_n(uint32_t n, uint32_t m) { +#if ME_EXP == 2 + MATH(SFPU_BINARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, me_sub_n, n, m, 0, VectorMode::RC)); + exp_tile_init(); + for (uint32_t t = 0; t < n; ++t) { + exp_tile(t); + } +#else + MATH(SFPU_BINARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, me_subexp_n, n, m, 0, + VectorMode::RC)); +#endif +} +// dst[a] = exp(dst[a] - dst[m]) (fused SFPU) +NOINL void fsubexp(uint32_t a, uint32_t m) { + MATH(SFPU_BINARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, me_subexp, a, m, a, + VectorMode::RC)); +} + +// Item (head, q block): softmax over chunks of KC key tiles, online across chunks. Per (q tile, chunk): +// S = q K^T + mask (fp32, score region); m = row max of S (FPU reduce, tf32 operand: rel err 2^-11); +// giant-logit blocks (|S| up to 2.6e6): D = S - m1 in place, m2 = row max of D, m = m1 + m2 (err ~ |S| 2^-22); +// m_new = max(m_old, m), alpha = exp(m_old - m_new); P = exp(S - m_new) (fused SFPU, in place); +// O = alpha O + P V, l = alpha l + P @ ONES (state FIFO CB_ST across chunks; one chunk: O / l directly). +NOINL void att_item(const Item& it, bool two) { + const uint32_t L = seg_len(it); + const uint32_t nch = (L + KC - 1) / KC; + cb_wait_front(CB_AQ, QB * 2); + for (uint32_t c = 0; c < nch; ++c) { + const uint32_t p0 = c * KC, nk = gmin(KC, L - p0); + const bool last = c + 1 == nch; + uint32_t mk[KC]; + for (uint32_t j = 0; j < nk; ++j) { + mk[j] = key_mask(seg_key(it, p0 + j)); + } + cb_wait_front(CB_KV, 4 * KC); + for (uint32_t i = 0; i < it.nq; ++i) { + APROF(0); + // S (fp32) -> region (views S32: P / D pass, S32F: max) + cb_reserve_back(CB_S32, KC); + cb_reserve_back(CB_S32F, KC); + for (uint32_t j0 = 0; j0 < nk; j0 += SUB) { + const uint32_t n = gmin(SUB, nk - j0); + tile_regs_acquire(); + scores(i, j0, n, mk); + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_S32); + for (uint32_t jj = 0; jj < n; ++jj) { + pack_tile(jj, CB_S32, j0 + jj); + } + tile_regs_release(); + } + region_push(CB_S32); + region_push(CB_S32F); + APROFP(1); + rowmax(nk); + APROFP(2); + if (c < 2 && i == 0) { + probe(CB_MX, 0); + } + if (two) { // m1 -> CB_MF1; D = S - m1 in place -> m2 + cb_reserve_back(CB_MF1, 1); + tile_regs_acquire(); + bcast_m(0); + tile_regs_commit(); + tile_regs_wait(); + pack_to(0, CB_MF1, 0); + tile_regs_release(); + cb_push_back(CB_MF1, 1); + cb_pop_front(CB_MX, 1); + cb_wait_front(CB_S32, KC); + cb_wait_front(CB_MF1, 1); + for (uint32_t j0 = 0; j0 < nk; j0 += SUB) { + const uint32_t n = gmin(SUB, nk - j0); + tile_regs_acquire(); + for (uint32_t jj = 0; jj < n; ++jj) { + load(CB_S32, j0 + jj, jj); + } + load(CB_MF1, 0, 6); + for (uint32_t jj = 0; jj < n; ++jj) { + fsub(jj, 6, jj); + } + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_S32); + for (uint32_t jj = 0; jj < n; ++jj) { + pack_tile(jj, CB_S32, j0 + jj); // the slot S occupied: still the front of S32 + } + tile_regs_release(); + } + cb_pop_front(CB_S32, KC); + cb_reserve_back(CB_S32, KC); + cb_reserve_back(CB_S32F, KC); + region_push(CB_S32); + region_push(CB_S32F); + rowmax(nk); + } + // m_new = max(m_old, m), alpha = exp(m_old - m_new), shift = m_new (giant: m_new - m1, P from D) + cb_reserve_back(CB_MFN, 3); + tile_regs_acquire(); + bcast_m(0); + if (two) { + load(CB_MF1, 0, 3); + fadd(0, 3, 0); + } + if (c > 0) { + cb_wait_front(CB_ST, 4); + load(CB_ST, 3, 1); + fmax(0, 1, 0); + fsub(1, 0, 2); + fexp(2); + } + if (two) { + fsub(0, 3, 4); + } + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_MFN); + pack_tile(0, CB_MFN, 0); + pack_tile(2, CB_MFN, 1); + pack_tile(two ? 4 : 0, CB_MFN, 2); + tile_regs_release(); + cb_push_back(CB_MFN, 3); + cb_pop_front(CB_MX, 1); + if (two) { + cb_pop_front(CB_MF1, 1); + } + APROFP(3); + // P = exp(S - shift) (fused SFPU, in place: view AP) + cb_wait_front(CB_MFN, 3); + if (c < 2 && i == 0) { + probe(CB_MFN, 0); + probe(CB_MFN, 1); + } + cb_wait_front(CB_S32, KC); + cb_reserve_back(CB_AP, KC); + for (uint32_t j0 = 0; j0 < nk; j0 += SUB) { + const uint32_t n = gmin(SUB, nk - j0); + tile_regs_acquire(); + reconfig_data_format_srca(CB_S32); + copy_init(CB_S32); + for (uint32_t jj = 0; jj < n; ++jj) { + copy_tile(CB_S32, j0 + jj, jj); + } + load(CB_MFN, 2, 6); + mul_binary_tile_init(); + fsubexp_n(n, 6); + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_AP); + for (uint32_t jj = 0; jj < n; ++jj) { + pack_tile(jj, CB_AP, j0 + jj); + } + tile_regs_release(); + } + cb_pop_front(CB_S32, KC); + region_push(CB_AP); + APROFP(4); + // O = alpha O + P V, l = alpha l + P @ ONES + cb_wait_front(CB_AP, KC); + if (c == 0 && i == 0) { + probe(CB_AP, 0); + probe(CB_AP, 1); + } + const bool direct = last && c == 0; // one chunk: O / l straight to the output + if (direct) { + cb_reserve_back(CB_AO, 2); + } else { + cb_reserve_back(CB_ST, 4); + } + tile_regs_acquire(); + mm_init_n(CB_AP, CB_CONST, 0); + for (uint32_t j = 0; j < nk; ++j) { + mm_f(CB_AP, CB_CONST, j, C_ONES, 2); + } + mm_init_n(CB_AP, CB_KV, 0); + for (uint32_t j = 0; j < nk; ++j) { + for (uint32_t d = 0; d < 2; ++d) { + mm_f(CB_AP, CB_KV, j, 2 * KC + 2 * j + d, d); + } + } + if (c > 0) { + load(CB_ST, 0, 3); + load(CB_ST, 1, 4); + load(CB_ST, 2, 5); + load(CB_MFN, 1, 6); + fmul(3, 6, 3); + fadd(0, 3, 0); + fmul(4, 6, 4); + fadd(1, 4, 1); + fmul(5, 6, 5); + fadd(2, 5, 2); + } + if (direct) { + frecip(2); + fmul(0, 2, 0); + fmul(1, 2, 1); + } else { + load(CB_MFN, 0, 7); + } + tile_regs_commit(); + tile_regs_wait(); + if (direct) { + pack_reconfig_data_format(CB_AO); + pack_tile(0, CB_AO, 0); + pack_tile(1, CB_AO, 1); + } else { + pack_reconfig_data_format(CB_ST); + pack_tile(0, CB_ST, 0); + pack_tile(1, CB_ST, 1); + pack_tile(2, CB_ST, 2); + pack_tile(7, CB_ST, 3); + } + tile_regs_release(); + if (c > 0) { + cb_pop_front(CB_ST, 4); + } + if (direct) { + cb_push_back(CB_AO, 2); + } else { + cb_push_back(CB_ST, 4); + if (c < 2 && i == 0) { + cb_wait_front(CB_ST, 4); + for (uint32_t q = 0; q < 4; ++q) { + probe(CB_ST, q); + } + } + } + cb_pop_front(CB_AP, KC); + cb_pop_front(CB_MFN, 3); + APROFP(5); + aprof = false; + } + cb_pop_front(CB_KV, 4 * KC); + } + // O / l -> bf16 (several chunks) + for (uint32_t i = 0; nch > 1 && i < it.nq; ++i) { + cb_wait_front(CB_ST, 4); + cb_reserve_back(CB_AO, 2); + tile_regs_acquire(); + load(CB_ST, 0, 0); + load(CB_ST, 1, 1); + load(CB_ST, 2, 2); + frecip(2); + fmul(0, 2, 0); + fmul(1, 2, 1); + tile_regs_commit(); + tile_regs_wait(); + pack_reconfig_data_format(CB_AO); + pack_tile(0, CB_AO, 0); + pack_tile(1, CB_AO, 1); + tile_regs_release(); + cb_push_back(CB_AO, 2); + cb_pop_front(CB_ST, 4); + } + cb_pop_front(CB_AQ, QB * 2); +} + +NOINL void att(uint32_t l) { + Item it; + TPROF(192 + 2 * l); + const uint32_t n = n_jobs(l); + bool first = true; + for (uint32_t g = me.x; g < n; g += C) { + job_of(l, g, me.y, it); + if (ME_PROBE && l == 0 && first && me.x == 0 && me.y == 0) { + n_probe = 0; + } + aprof = l == 1 && first; + att_item(it, giant(l)); + if (ME_PROBE && l == 0 && first && me.x == 0 && me.y == 0) { + probe_fill(); + } + first = false; + } + TPROFP(193 + 2 * l); +} + +// ================================================================ waves +uint32_t tiles_qkv() { return me.nh * 2 * (DT + 1); } + +// after the residual stream of block l (l = -1: after the embedding): pool, LN1 and QKV(l + 1) +NOINL void tail(int l) { + const uint32_t l1 = (uint32_t)(l + 1); + if (l1 >= NL) { // QKV(l + 1) runs even past a debug stop (nl < L): the staging then holds block nl's q / k / v + return; + } + if (POOL && joint(l1)) { + pool(); + } + stats_out(); + qkv(l1); +} + +NOINL void wave_end(int l, bool store) { + if (store) { + for (uint32_t s = 0; s < RB; ++s) { + if (me.kd[s] == KD_PREFIX || me.kd[s] == KD_PATCH) { + x_out(s); + } + } + } + if (NW > 1) { + cb_pop_front(CB_X, RB * NXM); + } + cb_pop_front(CB_TAB, 2 * RB); + arena_end(l < 0 ? me.npe : ((uint32_t)l == NL - 1 ? me.npbl : me.npb)); +} + +} // namespace + +void kernel_main() { + me.x = get_arg_val(A_X); + me.y = get_arg_val(A_Y); + me.h0 = get_arg_val(A_H0); + me.nh = get_arg_val(A_NH); + me.n0 = get_arg_val(A_N0); + me.nx = get_arg_val(A_NX); + me.f0 = get_arg_val(A_F0); + me.nf = get_arg_val(A_NF); + me.npe = get_arg_val(A_NPE); + me.npb = get_arg_val(A_NPB); + me.npbl = get_arg_val(A_NPBL); + me.nl = get_common_arg_val(K_NL); + me.dump = get_common_arg_val(K_DUMP); + me.eps = get_common_arg_val(K_EPS); + me.inv_d = get_common_arg_val(K_INVD); + me.inv_t = get_common_arg_val(K_INVT); + + compute_kernel_hw_startup(CB_INX, CB_W, CB_OUT); + cb_wait_front(CB_CONST, N_CONST); + cb_wait_front(CB_CF32, N_CF32); + cb_wait_front(CB_PFX, NXM); + if constexpr (POOL) { // runtime valid frames (me_brisc init_consts) + g_nv = sync_value(W_NV); + me.inv_t = sync_value(W_INVN); + } + + // E: embedding (+ LN1 / QKV of block 0) + for (uint32_t w = 0; w < NW; ++w) { + kinds(w); + uint32_t act = 0; + for (uint32_t s = 0; s < RB; ++s) { + act |= (me.kd[s] == KD_PATCH ? 1u : 0u) << s; + } + residual_op(0, act); + tail(-1); + wave_end(-1, NW > 1 || (me.dump && me.nl == 0)); + } + for (uint32_t l = 0; l < me.nl; ++l) { + att(l); + for (uint32_t w = 0; w < NW; ++w) { + kinds(w); + if (NW > 1) { + x_from_xl(); + } + const uint32_t act = mlp_mask(l); + wprof = l == 1 && w == 0; + WPROF(0); + residual_op(1, act); + WPROFP(1); + stats_out(); + WPROFP(2); + fc1(act); + WPROFP(3); + residual_op(2, act); + if (NW > 1 && l + 1 >= NL && w + 1 < NW) { // no QKV tail: tell the BRISC the FC2 reads of INF are done + cb_reserve_back(CB_TOK, 1); + cb_push_back(CB_TOK, 1); + } + WPROFP(4); + if (tap_of(l) >= 0) { + tap_out(); + } + tail((int)l); + WPROFP(5); + wave_end((int)l, NW > 1 || (me.dump && l + 1 == me.nl)); + } + } +} diff --git a/code/tt_depthpro2/tt/mk_enc/program.py b/code/tt_depthpro2/tt/mk_enc/program.py new file mode 100644 index 0000000000000000000000000000000000000000..295de1574ac172decc150611cfb74280cd4d0ba7 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_enc/program.py @@ -0,0 +1,348 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The ENC megakernel: one persistent ``ttnn.generic_op`` program per (size, T, gh, gw, mode) that runs DepthPro2's +whole encoder (patch embed + prefix + every DINOv3 block) and writes the 4 tapped patch-token tensors. + +``MkEnc(device, weights, size, T, gh, gw, mode)`` folds and uploads the weights (one DRAM arena per phase), the +constants and the persistent staging / output buffers once; ``run(patches)`` only enqueues the program (no host sync, +trace-capturable) and returns ``taps`` (4 x bf16 TILE ``[T * Np, C]``; FOV mode: ``[T * (32 + Np), C]``, per frame the +prefix tile then the patch tiles). + +Contract (SPEC section 3): ``patches [T * Np, 768]`` bf16 TILE in DRAM, row ``t * Np + n`` = frame t's patch n in +raster order, columns in (c, ky, kx) order (``arena.patchify``); rows >= N of each frame are zero. +""" + +from __future__ import annotations + +import os +import struct +import time +from typing import Dict, List, Optional, Sequence, Tuple + +import torch + +from . import arena as A +from . import geometry as G + +KERNELS = {r: os.path.join(G.KDIR, f"me_{r}.cpp") for r in ("ncrisc", "brisc", "trisc")} +LN_EPS = 1e-5 + + +def _sources_hash() -> str: + import hashlib + + h = hashlib.sha1() + d = os.path.dirname(os.path.abspath(__file__)) + for sub_dir in ("", "kernels"): + p = os.path.join(d, sub_dir) + for n in sorted(os.listdir(p)): + if n.endswith((".py", ".cpp", ".hpp")): + with open(os.path.join(p, n), "rb") as f: + h.update(n.encode() + f.read()) + return h.hexdigest() + + +_SOURCES_AT_IMPORT = _sources_hash() + + +def _opt_level(name: str): + from ttnn._ttnn.operations.experimental.fabric_mux import KernelBuildOptLevel + + return getattr(KernelBuildOptLevel, name) + + +def env_options() -> Dict: + """``DEPTHPRO2_MK_ENC_OPTS`` (A/B knobs, comma-separated ``key=value``): ``exp`` (0 fp32 exp, 1 exp_21f), + ``giant_all`` (0/1), ``fc1p`` (0/1), ``fid`` (HiFi4 / HiFi3 / ...).""" + out: Dict = {} + for kv in os.environ.get("DEPTHPRO2_MK_ENC_OPTS", "").split(","): + if "=" not in kv: + continue + k, v = (t.strip() for t in kv.split("=", 1)) + if k == "exp": + out["exp_mode"] = int(v) + elif k == "giant_all": + out["giant_all"] = bool(int(v)) + elif k == "fc1p": + out["fc1p_ok"] = bool(int(v)) + elif k == "fid": + out["fidelity"] = v + else: + raise ValueError(f"DEPTHPRO2_MK_ENC_OPTS: unknown key {k!r}") + return out + + +def f32_bits(x: float) -> int: + return struct.unpack(" List: + return [self.arena_e, *self.arenas, self.pfx] + + +def _vf_tile(n: int) -> torch.Tensor: + t = torch.zeros(1, 1, 32, 32, dtype=torch.int32) + t[0, 0, 0, 0] = n + t[0, 0, 0, 1] = f32_bits(1.0 / n) + return t + + +class MkEnc: + def __init__(self, device, weights, size: str, T: int, gh: int, gw: int, + mode: str = "depth", rb: int = 0, qb: int = 0, kc: int = 32, fidelity: str = "HiFi4", probe: bool = False, prof: bool = False, + opt: str = "O2", + defines: Sequence[Tuple[str, str]] = (), timings: Optional[Dict] = None): + import ttnn + + self.device = device + g = device.compute_with_storage_grid_size() + self.grid = (int(g.x), int(g.y)) + env = env_options() + fidelity = env.pop("fidelity", fidelity) + self.geo = geo = G.Geometry(size, T, gh, gw, mode, self.grid[0], self.grid[1], rb=rb, qb=qb, kc=kc, + probe=probe, prof=prof, **env) + self.fidelity = fidelity + self.opt = opt # TRISC build optimization level (the kernel-config buffer holds every binary: ~70 KB) + fid = {"LoFi": 0, "HiFi2": 2, "HiFi3": 3, "HiFi4": 4}[fidelity] + self.defines = list(geo.defines()) + list(defines) + ([("ME_FID", str(fid))] if fidelity != "HiFi4" else []) + self._noc: Dict[Tuple[int, int], Tuple[int, int]] = {} + for x in range(self.grid[0]): + for y in range(self.grid[1]): + c = device.worker_core_from_logical_core(ttnn.CoreCoord(x, y)) + self._noc[(x, y)] = (int(c.x), int(c.y)) + for x in range(self.grid[0] - 1): # logical order must be NoC order (rectangles map corner to corner) + if self._noc[(x, 0)][0] >= self._noc[(x + 1, 0)][0]: + raise RuntimeError("logical x order differs from NoC x order") + for y in range(self.grid[1] - 1): + if self._noc[(0, y)][1] >= self._noc[(0, y + 1)][1]: + raise RuntimeError("logical y order differs from NoC y order") + dram = ttnn.DRAM_MEMORY_CONFIG + if isinstance(weights, dict): + weights = MkEncWeights(device, weights, size, mode, rb=rb, timings=timings) + if (weights.size, weights.mode, weights.rb, weights.grid) != (size, mode, geo.rb, self.grid): + raise ValueError(f"prepared weights {weights.size}/{weights.mode}/rb {weights.rb}/{weights.grid} do not match " + f"{size}/{mode}/rb {geo.rb}/{self.grid}") + self.weights = weights + self.arena_e, self.arenas, self.pfx = weights.arena_e, weights.arenas, weights.pfx + t2 = time.perf_counter() + tile = lambda t, dt: ttnn.from_torch(t.contiguous(), dtype=dt, layout=ttnn.TILE_LAYOUT, # noqa: E731 + device=device, memory_config=dram) + self.consts = tile(A.const_tiles().reshape(-1, 32), ttnn.bfloat16) + self.cf32 = tile(A.cf32_tiles(geo.nlast).reshape(-1, 32), ttnn.float32) + self.rope = tile(A.rope_tiles(gh, gw, geo.Pt), ttnn.float32) + z = lambda rows, dt: tile(torch.zeros(rows, geo.dim), dt) # noqa: E731 + z4 = lambda rows, dt: tile(torch.zeros(1, 1, rows, geo.dim), dt) # noqa: E731 + mt32 = geo.Mt * 32 + self.xd = z(mt32, ttnn.float32) + self.q, self.k, self.v, self.o = (z(mt32, ttnn.bfloat16) for _ in range(4)) + tap_rows = T * (geo.Np + 32) if mode == "fov" else T * geo.Np + self.taps = [z4(tap_rows, ttnn.bfloat16) for _ in range(4)] # [1, 1, rows, C] (the ttnn engines' shape) + self.prb = tile(torch.zeros(G.N_PROBE * 32, 32), ttnn.float32) + # runtime valid-frame count (set_valid_frames; read by the kernels when T > 1): [n, bits(1 / n)] + self.vf = ttnn.from_torch(_vf_tile(T), dtype=ttnn.uint32, layout=ttnn.TILE_LAYOUT, device=device, + memory_config=dram) + self.valid_frames = T + self.prof = ttnn.from_torch(torch.zeros(1, 1, geo.NC, G.PROF_WORDS, dtype=torch.int32), dtype=ttnn.uint32, + layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram) + self._acc = list(ttnn.TensorAccessorArgs(self.q).get_compile_time_args()) + self._desc: Dict[Tuple, object] = {} + if timings is not None: + timings["mk_enc_consts_s"] = time.perf_counter() - t2 + + # ------------------------------------------------------------------ args + def noc(self, xy) -> Tuple[int, int]: + return self._noc[tuple(xy)] + + def persistent(self) -> List: + return [self.arena_e, *self.arenas, self.consts, self.cf32, self.rope, self.pfx, self.xd, self.q, self.k, + self.v, self.o, self.prb, self.prof, self.vf] + + def set_valid_frames(self, n: int) -> None: + """The next runs / trace replays process frames ``[0, n)`` as an n-frame clip (BASELINE.md 9.2: frames >= n + must be zero patches; their taps are don't-care). Host call: one 4 KB write to a persistent DRAM tile on CQ 0 + (no allocation, no compile, no sync).""" + import ttnn + + n = int(n) + if not 1 <= n <= self.geo.T: + raise ValueError(f"valid frames {n} outside [1, {self.geo.T}]") + if self.geo.pool: + host = ttnn.from_torch(_vf_tile(n), dtype=ttnn.uint32, layout=ttnn.TILE_LAYOUT) + ttnn.copy_host_to_device_tensor(host, self.vf) + elif n != self.geo.T: + raise ValueError("this program has no cross-frame pool (T = 1 or FOV mode): n must equal T") + self.valid_frames = n + + def common_args(self, patches, nl: int, dump: bool) -> List[int]: + geo = self.geo + c = [0] * G.N_COMMON_ARGS + c[G.K_ALL_X0:G.K_ALL_Y1 + 1] = geo.rect(self.noc) + c[G.K_N_ALL] = geo.NC + c[G.K_HUB_X], c[G.K_HUB_Y] = self.noc(geo.hub()) + c[G.K_NL] = int(nl) + c[G.K_DUMP] = int(bool(dump)) + c[G.K_EPS] = f32_bits(LN_EPS) + c[G.K_INVD] = f32_bits(1.0 / geo.dim) + c[G.K_INVT] = f32_bits(1.0 / geo.T) + c[G.K_PATCH] = patches.buffer_address() + for i in range(4): + c[G.K_TAP0 + i] = self.taps[i].buffer_address() + c[G.K_XD] = self.xd.buffer_address() + c[G.K_Q], c[G.K_K], c[G.K_V], c[G.K_O] = (t.buffer_address() for t in (self.q, self.k, self.v, self.o)) + c[G.K_CONST] = self.consts.buffer_address() + c[G.K_CF32] = self.cf32.buffer_address() + c[G.K_ROPE] = self.rope.buffer_address() + c[G.K_PFX] = self.pfx.buffer_address() + c[G.K_ARENA_E] = self.arena_e.buffer_address() + for i, a in enumerate(self.arenas): + c[G.K_ARENA0 + i] = a.buffer_address() + c[G.K_PROBE] = self.prb.buffer_address() + c[G.K_PROF] = self.prof.buffer_address() + c[G.K_VF] = self.vf.buffer_address() + return c + + def program(self, patches, nl: Optional[int] = None, dump: bool = False): + import ttnn + + geo = self.geo + nl = geo.L if nl is None else int(nl) + common = self.common_args(patches, nl, dump) + key = tuple(common) + if key in self._desc: + return self._desc[key] + if _sources_hash() != _SOURCES_AT_IMPORT: # a new program compiles the kernel files as they are NOW + raise RuntimeError("tt/mk_enc sources changed since this process imported them (kernel / host skew would " + "compute garbage): restart the process") + gx, gy = self.grid + cores = ttnn.CoreRangeSet([ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(gx - 1, gy - 1))]) + fmt = {"bf16": ttnn.bfloat16, "fp32": ttnn.float32, "raw": ttnn.bfloat16} + cbs = [] + modes = [ttnn.UnpackToDestMode.Default] * 64 + for ids, total in geo.cb_table(): + fds = [] + for cb_id, f, unpack32 in ids: + page = total if f == "raw" else (G.T16 if f == "bf16" else G.T32) + fds.append(ttnn.CBFormatDescriptor(buffer_index=cb_id, data_format=fmt[f], page_size=page)) + if unpack32: + modes[cb_id] = ttnn.UnpackToDestMode.UnpackToDestFp32 + cbs.append(ttnn.CBDescriptor(total_size=total, core_ranges=cores, format_descriptors=fds)) + ct = list(self._acc) + args = geo.core_args(self.noc) + rt = ttnn.RuntimeArgs() + for x in range(gx): + for y in range(gy): + rt[x][y] = args[(x, y)] + cc = ttnn.ComputeConfigDescriptor(math_fidelity=getattr(ttnn.MathFidelity, self.fidelity), + fp32_dest_acc_en=True, dst_full_sync_en=True, math_approx_mode=False) + cc.unpack_to_dest_mode = modes + defines = list(self.defines) + [("ME_OPT_" + self.opt, "1")] # the JIT disk cache key ignores opt_level + fp = ttnn.KernelDescriptor.SourceType.FILE_PATH + dm = ttnn.DataMovementConfigDescriptor + kernels = [ + ttnn.KernelDescriptor(kernel_source=KERNELS["ncrisc"], source_type=fp, core_ranges=cores, + compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines, + config=dm(processor=ttnn.DataMovementProcessor.RISCV_1, noc=ttnn.NOC.NOC_0)), + ttnn.KernelDescriptor(kernel_source=KERNELS["brisc"], source_type=fp, core_ranges=cores, + compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines, + config=dm(processor=ttnn.DataMovementProcessor.RISCV_0, noc=ttnn.NOC.NOC_1)), + ttnn.KernelDescriptor(kernel_source=KERNELS["trisc"], source_type=fp, core_ranges=cores, + compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines, + config=cc, opt_level=_opt_level(self.opt)), + ] + sems = [ttnn.SemaphoreDescriptor(id=i, core_ranges=cores, initial_value=0) for i in (0, 1)] + desc = ttnn.ProgramDescriptor(kernels=kernels, semaphores=sems, cbs=cbs) + self._desc[key] = desc + return desc + + def run(self, patches, nl: Optional[int] = None, dump: bool = False) -> List: + """Enqueue the ENC program (one ``generic_op``); returns the 4 taps. ``nl`` < L (debug): run only the first + ``nl`` blocks (``dump``: x (fp32) of the last block run is stored to ``self.xd``).""" + import ttnn + + io = [*self.persistent(), patches, *self.taps] + ttnn.generic_op(io, self.program(patches, nl, dump)) + return self.taps + + # ------------------------------------------------------------------ debug readers + def read_x(self) -> torch.Tensor: + """x (fp32) per row tile ``[Mt, 32, dim]`` from XD (after a ``dump`` run, or always with W > 1).""" + import ttnn + + return ttnn.to_torch(self.xd).float().reshape(self.geo.Mt, 32, self.geo.dim) + + def read_prof(self) -> torch.Tensor: + import ttnn + + return ttnn.to_torch(self.prof).reshape(self.geo.NC, G.PROF_WORDS).to(torch.int64) & 0xFFFFFFFF + + def read_probe(self) -> torch.Tensor: + import ttnn + + return ttnn.to_torch(self.prb).float().reshape(G.N_PROBE, 32, 32) + + def read_stage(self, which: str) -> torch.Tensor: + import ttnn + + t = {"q": self.q, "k": self.k, "v": self.v, "o": self.o}[which] + return ttnn.to_torch(t).float().reshape(self.geo.Mt, 32, self.geo.dim) + + +class Engine: + """SPEC section 3 stage-engine adapter (``tt/__init__.py`` contract): ``Engine(device, weights, shape)`` with + ``weights`` = :meth:`prepare_weights` (shared by every shape) or the host dict (+ ``size``); ``run(patches)`` + -> 4 taps ``[1, 1, T * Np, C]`` bf16 TILE (FOV mode: ``[1, 1, T * (32 + Np), C]``, per frame the prefix tile, then + the patch tiles). + + Runtime valid-frame count (BASELINE.md 9.2): ``supports_valid_frames``; ``set_valid_frames(n)`` before a run / trace + replay makes the T-frame program process frames ``[0, n)`` as an n-frame clip (depth mode, T > 1).""" + + supports_valid_frames = True + + def __init__(self, device, weights, shape, size: Optional[str] = None, mode: str = "depth", **kw): + if isinstance(weights, dict): + if size is None: + raise ValueError("size is required with host weights") + weights = MkEncWeights(device, weights, size, mode) + self.shape = shape + self.mk = MkEnc(device, weights, weights.size, shape.frames, shape.hp // 16, shape.wp // 16, + mode=weights.mode, **kw) + + @staticmethod + def prepare_weights(device, host_weights, size: str, mode: str = "depth") -> MkEncWeights: + return MkEncWeights(device, host_weights, size, mode) + + def set_valid_frames(self, n: int) -> None: + self.mk.set_valid_frames(n) + + def input_spec(self): + return (1, 1, self.shape.frames * self.mk.geo.Np, 768), "bf16 TILE DRAM" + + def run(self, patches) -> List: + return self.mk.run(patches) diff --git a/code/tt_depthpro2/tt/mk_fov/__init__.py b/code/tt_depthpro2/tt/mk_fov/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e7a651f32582f8e1a55b9d39fd5982f6a866b64d --- /dev/null +++ b/code/tt_depthpro2/tt/mk_fov/__init__.py @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: Apache-2.0 +"""FOV stage, megakernel engine: the ENC megakernel in FOV-trunk mode (tt/mk_enc) + the ttnn float32 head.""" + +from .engine import Engine, MkFovWeights # noqa: F401 diff --git a/code/tt_depthpro2/tt/mk_fov/engine.py b/code/tt_depthpro2/tt/mk_fov/engine.py new file mode 100644 index 0000000000000000000000000000000000000000..572e68b07b2c6b1c02adb4999e845f044c5156a8 --- /dev/null +++ b/code/tt_depthpro2/tt/mk_fov/engine.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: Apache-2.0 +"""FOV stage, megakernel engine (``engine={"fov": "mk"}``). + +Stage contract (BASELINE.md §2, same as ``tt/ttnn_fov.py``): + +* ``FOV.in`` ``fpatches`` ``[1, 1, T * Nfp, 768]`` bf16 TILE DRAM (``reference.fov_resize`` frames, unfolded like + ``ENC.in``; rows ``>= gh * gw`` of each frame zero); +* ``FOV.out`` ``logits`` ``[1, 1, T, 2]`` float32 TILE DRAM. + +Trunk: the ENC megakernel in FOV mode (:class:`tt.mk_enc.MkEnc`, ``mode="fov"``: DINOv3 ViT-S/16, blocks 5 / 7 / 9 / 11 +keep their input prefix, no joint attention, taps after blocks 2 / 5 / 8 / 11 incl. the prefix). Its taps are +``[1, 1, T * (32 + Np), 384]`` bf16: per frame one prefix tile (rows 0..4 = cls, reg0..3; rows 5..31 finite filler) +and then the ``Np`` patch rows (rows ``>= N`` finite filler). + +Head: the float32 head of ``tt/ttnn_fov.py`` (its methods are reused unchanged through a subclass that skips the +ttnn trunk); only the constant gather / pooling matrix differs (it reads the megakernel's tap layout). Frames are +independent, so a T-frame program serves any n <= T frames (zero frames in the unused slots, outputs ``[:n]``). +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Optional, Tuple + +import torch + +from ...reference import model as ref +from .. import NUM_PREFIX, StageShape, ceil32 +from .. import ttnn_fov +from ..mk_enc.program import MkEnc, MkEncWeights +from ..ttnn_enc import Configs, _ttnn, exact_layer_norm, full_view, same_buffer +from ..weights import FOV_HD, FovHeadWeights, dev_tensor, upload_fov_head + +TRUNK_DIM = ref.FOV_TRUNK.dim # 384 + + +def mk_head_gather(gh: int, gw: int, np_: int) -> Tuple[torch.Tensor, int]: + """``G^T`` ``[32 + Np, S_hp]`` (float32) and ``S_h`` for the megakernel's FOV tap layout: head row 0 = query slot + (zero), rows 1..5 = prefix rows 0..4, rows 6.. = ceil-mode 2x2 average of the patch grid (patch p at row 32 + p); + weights 1, 1/2, 1/4 (exact in bf16). Same head sequence as ``ttnn_fov.head_gather``.""" + lm = 32 + np_ + ph, pw = -(-gh // 2), -(-gw // 2) + s_h = 1 + NUM_PREFIX + ph * pw + g = torch.zeros(ceil32(s_h), lm) + for j in range(NUM_PREFIX): + g[1 + j, j] = 1.0 + for a in range(ph): + for b in range(pw): + rows = [r for r in (2 * a, 2 * a + 1) if r < gh] + cols = [c for c in (2 * b, 2 * b + 1) if c < gw] + wgt = 1.0 / (len(rows) * len(cols)) + for r in rows: + for c in cols: + g[1 + NUM_PREFIX + a * pw + b, 32 + r * gw + c] = wgt + return g.t().contiguous(), s_h + + +class MkFovWeights: + """FOV weights uploaded once: the trunk's megakernel arenas (:class:`MkEncWeights`, mode "fov") and the ttnn + float32 head weights (``weights.upload_fov_head``); shared by every FOV shape.""" + + def __init__(self, device, host_weights, rb: int = 0): + self.trunk = MkEncWeights(device, host_weights, "S", "fov", rb=rb) + self.head: FovHeadWeights = upload_fov_head(device, host_weights) + self.size, self.mode = "S", "fov" + + +class _Head(ttnn_fov.Engine): + """The ttnn FOV head (``ttnn_fov.Engine`` methods ``_ln`` / ``_lin`` / ``_attn32`` / ``_head_block``) without + its ttnn trunk, on the megakernel's tap layout.""" + + def __init__(self, device, head: FovHeadWeights, shape: StageShape, np_: int): # noqa: D401 (no super().__init__) + ttnn = _ttnn() + self.device = device + self.shape = shape + self.w = SimpleNamespace(head=head) + self.cfgs = Configs(device) + self.mem = ttnn.DRAM_MEMORY_CONFIG + gt, s_h = mk_head_gather(shape.gh, shape.gw, np_) + self.s_h, self.s_hp = s_h, gt.shape[1] + self.gather_t = dev_tensor(gt.reshape(1, 1, *gt.shape), device) + ph, pw = -(-shape.gh // 2), -(-shape.gw // 2) + add = torch.zeros(1, 1, self.s_hp, FOV_HD) + add[0, 0, 0] = head.query_host + add[0, 0, 1:1 + NUM_PREFIX] = head.prefix_embed_host + add[0, 0, 1 + NUM_PREFIX:s_h] = ref.sincos_2d(ph, pw, FOV_HD) + self.head_add_host = add + self.head_pc = self.cfgs.sdpa_program(s_h, s_h) + import os + + self.head32 = os.environ.get("DEPTHPRO2_TTNN_FOV_HEAD", "fp32") == "fp32" + self.act = ttnn.float32 if self.head32 else ttnn.bfloat16 + self.head_add = dev_tensor(add, device, dtype=self.act) + if self.head32: + cm = torch.ones(1, 1, 1, FOV_HD) + self.colmask = dev_tensor(cm, device, dtype=ttnn.float32) + + def head(self, taps) -> object: + """4 megakernel taps ``[1, 1, T * (32 + Np), 384]`` -> logits ``[1, 1, T, 2]`` float32 (``ttnn_fov.Engine.run`` + after its trunk).""" + ttnn = _ttnn() + T = self.shape.frames + hw = self.w.head + lm = taps[0].padded_shape[-2] // T + normed = [] + for i, t in enumerate(taps): # the taps are the megakernel's persistent outputs: views only, never freed + v = ttnn.reshape(t, [T, 1, lm, TRUNK_DIM]) + normed.append(exact_layer_norm(v, hw.tap_n_w[i], hw.tap_n_b[i], ref.LN_EPS, self.mem, self.cfgs.ln)) + if not same_buffer(v, t): + ttnn.deallocate(v) + cat = ttnn.concat(normed, dim=-1, memory_config=self.mem) # [T, 1, Lm, 1536] + for t in normed: + ttnn.deallocate(t) + y = self._lin(cat, hw.proj_w, hw.proj_b) # [T, 1, Lm, 248] + ttnn.deallocate(cat) + yt = ttnn.transpose(y, -2, -1, memory_config=self.mem) # [T, 1, 248, Lm] + ttnn.deallocate(y) + zt = ttnn.matmul(yt, self.gather_t, memory_config=self.mem, dtype=self.act, compute_kernel_config=self.cfgs.mm) + ttnn.deallocate(yt) + z = ttnn.transpose(zt, -2, -1, memory_config=self.mem) # [T, 1, S_hp, 248] + ttnn.deallocate(zt) + x = ttnn.add(z, self.head_add, memory_config=self.mem) + ttnn.deallocate(z) + for p in hw.blocks: + x2 = self._head_block(x, p) + ttnn.deallocate(x) + x = x2 + q0 = ttnn.slice(full_view(x), [0, 0, 0, 0], [T, 1, 32, FOV_HD], memory_config=self.mem) + ttnn.deallocate(x) + h = self._ln(q0, hw.norm_w, hw.norm_b) + ttnn.deallocate(q0) + lg = ttnn.linear(h, hw.out_w, bias=hw.out_b, memory_config=self.mem, dtype=ttnn.float32, + compute_kernel_config=self.cfgs.mm) # [T, 1, 32, 2] float32 + ttnn.deallocate(h) + r0 = ttnn.slice(lg, [0, 0, 0, 0], [T, 1, 1, 2], memory_config=self.mem) + ttnn.deallocate(lg) + return ttnn.reshape(r0, [1, 1, T, 2], memory_config=self.mem) + + +class Engine: + """FOV stage engine for one :class:`StageShape` (the fov-resized size): ``run(fpatches) -> logits [1, 1, T, 2]`` + float32. ``weights``: :meth:`prepare_weights` (shared by every shape) or the DepthPro2-focal host dict.""" + + def __init__(self, device, weights, shape: StageShape, size: Optional[str] = None, **kw): + if isinstance(weights, dict): + weights = Engine.prepare_weights(device, weights) + self.shape = shape + self.weights = weights + self.mk = MkEnc(device, weights.trunk, "S", shape.frames, shape.gh, shape.gw, mode="fov", **kw) + self._head = _Head(device, weights.head, shape, self.mk.geo.Np) + + @staticmethod + def prepare_weights(device, host_weights, size: str = "fov") -> MkFovWeights: + return MkFovWeights(device, host_weights) + + def input_spec(self): + return (1, 1, self.shape.frames * self.mk.geo.Np, 768), "bf16 TILE DRAM" + + def run(self, fpatches) -> object: + return self._head.head(self.mk.run(fpatches)) diff --git a/code/tt_depthpro2/tt/model.py b/code/tt_depthpro2/tt/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7b00d4693872b6e384a176cc36afadd528f99151 --- /dev/null +++ b/code/tt_depthpro2/tt/model.py @@ -0,0 +1,582 @@ +# SPDX-License-Identifier: Apache-2.0 +"""``DepthPro2Device``: the host/device boundary of the DepthPro2 port (SPEC §3). + +Per compiled configuration (T frames at a padded bucket ``Hp x Wp``) the device holds one persistent input tensor +(the unfolded patches), the ENC and DEC engines and ONE trace (ENC + DEC). ``inverse_depth(x)`` = host unfold -> +``copy_host_to_device_tensor`` -> ``execute_trace`` -> readback. The FOV estimator has its own traces per +``(T, h, w)`` of the fov-resized frames. + +Engines per stage (``engine={"enc": "mk"|"ttnn", "dec": ..., "fov": ...}``, default all ``"ttnn"``): the module +``tt._`` must export ``Engine`` (contract in ``tt/__init__.py``); ``mk`` modules are imported lazily. + +Configurations are compiled in three phases: (1) every engine and persistent tensor is created, (2) every engine runs +once eagerly (program compile, conv weight preparation), (3) every trace is captured. Nothing is allocated after the +first capture. A call with a (T, size) that was not compiled releases every trace, compiles the new configuration and +recaptures everything (slow; logged as a warning). + +Runtime valid-frame count: an n-frame call runs the smallest compiled T >= n (zero frames in slots n..T-1) after +``Engine.set_valid_frames(n)`` when the ENC engine has ``supports_valid_frames`` (ttnn: yes); else T = n exactly. + +Unbuffered video: ``kv_cache(bucket, window)`` / ``inverse_depth_step(x, cache)`` (``tt/ttnn_kv.py``; the semantics +of ``cpu_engine.CPUEngine``), one step trace per cache slot, ring of ``max_frames`` frames. + +Trace-region sizing: :func:`trace_region_bytes`; one KV cache's DRAM: :func:`kv_state_bytes`. + +Device-open requirements (ttnn engines): ``l1_small_size >= 32768`` (conv2d), a trace region large enough for all +traces (measured per configuration, ENC + DEC + FOV: ~16 MB (S) to ~28 MB (H+) at 480x640 T=1; the DEC trace grows +with T x resolution, ~142 MB at 1088x1920 T=16; logs/depthpro2/baseline/BASELINE.md §5), ETH dispatch recommended. + +Example:: + + import ttnn + from tt_depthpro2.reference import model as ref + from tt_depthpro2.tt.model import DepthPro2Device + from tt_depthpro2.tt.weights import load_weights + + dev = ttnn.open_device(device_id=0, l1_small_size=32768, trace_region_size=256 << 20, + dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH)) + m = DepthPro2Device(dev, "S", load_weights(".../DepthPro2-S"), load_weights(".../DepthPro2-focal"), + buckets=[(480, 640)], max_frames=4, frames=(1,)) + x = ref.pad_to_multiple(ref.preprocess(frames_u8)) # [T, 3, 480, 640] + inv = m.inverse_depth(x) # [T, 480, 640] float32 + logits = m.fov_logits(ref.fov_resize(ref.preprocess(frames_u8))) + m.close(); ttnn.close_device(dev) +""" + +from __future__ import annotations + +import importlib +import logging +import os +import time +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence, Tuple + +import torch + +from ..reference import model as ref +from . import StageShape +from .weights import unfold_patches + +log = logging.getLogger(__name__) + +STAGES = ("enc", "dec", "fov") +ENGINES = ("ttnn", "mk") + + +def _norm_size(size: str) -> str: + s = size.strip().upper().rstrip("+") + if s not in ref.SIZES: + raise ValueError(f"unknown DepthPro2 size {size!r} (S, B, L, H)") + return s + + +def engine_class(stage: str, engine: str): + """``tt._.Engine`` (``mk`` modules are imported only when requested).""" + if stage not in STAGES or engine not in ENGINES: + raise ValueError(f"engine {engine!r} for stage {stage!r}: expected stage in {STAGES}, engine in {ENGINES}") + mod = f"{__package__}.{engine}_{stage}" + try: + m = importlib.import_module(mod) + cls = getattr(m, "Engine", None) # a package may import its Engine lazily + except Exception as e: # noqa: BLE001 (missing / half-written mk module: a clear error naming it) + raise RuntimeError(f"DepthPro2 engine {engine!r} for stage {stage!r} needs module {mod}, which is not usable " + f"({type(e).__name__}: {e}); use engine {{'{stage}': 'ttnn'}} instead") from e + if cls is None: + raise RuntimeError(f"{mod} does not export Engine") + return cls + + +@dataclass +class _Program: + """One traced configuration: engines, persistent input, output of the last capture, trace id.""" + + shape: StageShape + engines: List[object] + inp: object + out: object = None + trace: Optional[int] = None + warm: bool = False + stats: Dict[str, float] = field(default_factory=dict) + run: Optional[object] = None # callable(inp) -> output (else the engines are chained) + + +def parse_engine(engine) -> Dict[str, str]: + """``None`` | ``"mk"`` | ``"ttnn"`` | ``"enc=mk,dec=ttnn"`` | dict -> ``{stage: kind}`` for every stage (default ttnn).""" + out = {s: "ttnn" for s in STAGES} + if engine is None: + return out + if isinstance(engine, str): + e = engine.strip() + if e in ENGINES: + return {s: e for s in STAGES} + engine = dict(kv.split("=", 1) for kv in e.split(",") if kv.strip()) + for k, v in dict(engine).items(): + k, v = str(k).strip(), str(v).strip() + if k not in STAGES or v not in ENGINES: + raise ValueError(f"engine {k}={v!r}: stages {STAGES}, kinds {ENGINES}") + out[k] = v + return out + + +class KVCache: + """Handle of one unbuffered-video key-value cache (one stream) for one bucket (``DepthPro2Device.kv_cache``): + ``reset()``, ``close()``, ``frames`` (frames held, ``<= window``). Same semantics as ``cpu_engine.CPUKVCache``.""" + + def __init__(self, owner: "DepthPro2Device", bucket: Tuple[int, int], window: int, slot: "_KVSlot"): + self._owner = owner + self.bucket = tuple(bucket) + self.window = int(window) + self._slot = slot + self.seen = 0 + self.closed = False + + @property + def frames(self) -> int: + return min(self.seen, self.window) + + @property + def nbytes(self) -> int: + """Device bytes of this cache's ring state (the compiled ring holds ``max_frames - 1`` previous frames).""" + return self._slot.state.nbytes + + def reset(self) -> None: + self.seen = 0 + + def close(self) -> None: + if not self.closed: + self.closed = True + self._owner._release_kv(self) + + +@dataclass +class _KVSlot: + """A device ring state plus the step trace bound to it (one per concurrently open cache).""" + + state: object + program: _Program + in_use: bool = False + + +class DepthPro2Device: + """See the module doc. + + Keywords beyond SPEC §3 (``api.py`` passes them when present): + + * ``fov_shapes``: the fov-resized ``(h, w)`` sizes to compile (default ``fov_size`` of every bucket); + * ``clip_lengths``: clip lengths the caller will use (``"all"`` = 1..max_frames). With an ENC engine that has a + runtime valid-frame count (``Engine.supports_valid_frames``; the ttnn engine has it) only T = ``max_frames`` + and (if 1 is asked for) T = 1 are compiled and any n <= max_frames is served by the smallest compiled T >= n; + otherwise every asked length is compiled exactly; + * ``precision``: ``None`` / ``"bf16"`` (the only gated precision; bf16 weights, fp32 residual stream); + * ``kv_cache``: build the unbuffered-video step programs (``kv_cache`` / ``inverse_depth_step``) for every bucket + with a ring of ``max_frames`` frames; ``kv_streams`` caches per bucket are allocated up front (more are added on + demand: all traces are recaptured, slow). + """ + + supports_kv_cache = True + + def __init__(self, device, size: str, size_weights: dict, fov_weights: Optional[dict], + buckets: Sequence[Tuple[int, int]], max_frames: int, engine: Optional[dict] = None, + frames: Optional[Sequence[int]] = None, fov_shapes: Optional[Sequence[Tuple[int, int]]] = None, + clip_lengths=None, precision: Optional[str] = None, kv_cache: bool = False, + kv_streams: Optional[int] = None): + import ttnn + + self.device = device + self.size = _norm_size(size) + self.cfg = ref.SIZES[self.size] + self.engine = parse_engine(engine) + if precision not in (None, "bf16"): + raise ValueError(f"precision={precision!r}: the device engines run bf16 weights (the only gated precision)") + self.precision = "bf16" + self.buckets = [(int(h), int(w)) for h, w in buckets] + for h, w in self.buckets: + if h % 32 or w % 32: + raise ValueError(f"bucket {h}x{w}: padded sizes must be multiples of 32") + self.max_frames = int(max_frames) + if not 1 <= self.max_frames <= 64: + raise ValueError(f"max_frames {max_frames} outside 1..64") + self._cls = {s: engine_class(s, self.engine[s]) for s in ("enc", "dec")} + self.valid_frames = bool(getattr(self._cls["enc"], "supports_valid_frames", False)) + if isinstance(clip_lengths, str): + if clip_lengths != "all": + raise ValueError(f"clip_lengths={clip_lengths!r}: 'all' or a list of lengths") + asked = set(range(1, self.max_frames + 1)) + else: + asked = {int(t) for t in (clip_lengths or ())} + asked |= {self.max_frames, *(int(t) for t in (frames or ()))} + if any(not 1 <= t <= self.max_frames for t in asked): + raise ValueError(f"clip lengths {sorted(asked)} outside 1..{self.max_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._weights = { + "enc": self._prepare(self._cls["enc"], size_weights, self.size), + "dec": self._prepare(self._cls["dec"], size_weights, self.size), + } + self.has_fov = fov_weights is not None + if self.has_fov: + self._cls["fov"] = engine_class("fov", self.engine["fov"]) + self._weights["fov"] = self._prepare(self._cls["fov"], fov_weights, "fov") + self.last_timing: Dict[str, float] = {} + self._depth: Dict[Tuple[int, int, int], _Program] = {} + self._fov: Dict[Tuple[int, int, int], _Program] = {} + self._kv: Dict[Tuple[int, int], dict] = {} + self._size_weights = size_weights + self._captured = False + t0 = time.perf_counter() + if self.has_fov: + fs = fov_shapes if fov_shapes is not None else [self.fov_size(h, w) for h, w in self.buckets] + self.fov_shapes = sorted({(int(h), int(w)) for h, w in fs}) + else: + self.fov_shapes = [] + for h, w in self.buckets: + for t in self.frame_counts: + self._build_depth(StageShape(t, h, w)) + for h, w in self.fov_shapes: + for t in self.frame_counts: + self._build_fov(StageShape(t, h, w)) + self.kv_streams = int(kv_streams if kv_streams is not None else os.environ.get("DEPTHPRO2_KV_STREAMS", "1")) + if kv_cache: + for h, w in self.buckets: + for _ in range(max(1, self.kv_streams)): + self._add_kv_slot((h, w)) + self._warm_all() + self._capture_all() + self.compile_seconds = time.perf_counter() - t0 + self._ttnn = ttnn + + # ------------------------------------------------------------------------------------------- setup + def _prepare(self, cls, host, size): + prep = getattr(cls, "prepare_weights", None) + return prep(self.device, host, size) if prep is not None else host + + @staticmethod + def fov_size(h: int, w: int) -> Tuple[int, int]: + """Size of ``reference.fov_resize`` output for an ``h x w`` frame.""" + y = ref.fov_resize(torch.zeros(1, 3, h, w)) + return int(y.shape[-2]), int(y.shape[-1]) + + def _alloc_input(self, rows: int): + import ttnn + + host = ttnn.from_torch(torch.zeros(1, 1, rows, 768, dtype=torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT) + return ttnn.to_device(host, self.device, memory_config=ttnn.DRAM_MEMORY_CONFIG) + + def _build_depth(self, shape: StageShape) -> _Program: + key = (shape.frames, shape.hp, shape.wp) + if key not in self._depth: + enc = self._cls["enc"](self.device, self._weights["enc"], shape) + dec = self._cls["dec"](self.device, self._weights["dec"], shape) + self._depth[key] = _Program(shape, [enc, dec], self._alloc_input(shape.frames * shape.np_)) + return self._depth[key] + + def _build_fov(self, shape: StageShape) -> _Program: + key = (shape.frames, shape.hp, shape.wp) + if key not in self._fov: + fov = self._cls["fov"](self.device, self._weights["fov"], shape) + self._fov[key] = _Program(shape, [fov], self._alloc_input(shape.frames * shape.np_)) + return self._fov[key] + + def _kv_bucket(self, bucket: Tuple[int, int]) -> dict: + """Per-bucket step machinery: ttnn step encoder (always ttnn), T=1 decoder, shared persistent input.""" + from .ttnn_enc import Engine as TtnnEnc + from .ttnn_kv import StepEncoder + + kb = self._kv.get(bucket) + if kb is None: + shape = StageShape(1, *bucket) + if self.engine["enc"] == "ttnn": + tw = self._weights["enc"] + else: + tw = self._weights.setdefault("enc_ttnn", TtnnEnc.prepare_weights(self.device, self._size_weights, self.size)) + p1 = self._depth.get((1,) + tuple(bucket)) + dec = p1.engines[1] if p1 is not None else self._cls["dec"](self.device, self._weights["dec"], shape) + kb = self._kv[bucket] = {"shape": shape, "enc": StepEncoder(self.device, tw, shape, self.max_frames), + "dec": dec, "inp": self._alloc_input(shape.np_), "slots": []} + return kb + + def _add_kv_slot(self, bucket: Tuple[int, int]) -> _KVSlot: + from .ttnn_kv import KVState + + kb = self._kv_bucket(bucket) + state = KVState(self.device, kb["shape"], self.cfg, self.max_frames, self.cfg.cross_frame_blocks) + enc, dec = kb["enc"], kb["dec"] + prog = _Program(kb["shape"], [], kb["inp"], run=lambda inp, e=enc, d=dec, st=state: d.run(e.run(inp, st))) + slot = _KVSlot(state, prog) + kb["slots"].append(slot) + return slot + + @staticmethod + def _run_program(p: _Program): + if p.run is not None: + return p.run(p.inp) + x = p.inp + for e in p.engines: + x = e.run(x) + return x + + def _programs(self) -> List[_Program]: + kv = [s.program for kb in self._kv.values() for s in kb["slots"]] + return list(self._depth.values()) + list(self._fov.values()) + kv + + def _warm_all(self) -> None: + import ttnn + + for p in self._programs(): + if not p.warm: + t0 = time.perf_counter() + out = self._run_program(p) + ttnn.synchronize_device(self.device) + ttnn.deallocate(out) + p.warm = True + p.stats["warm_s"] = time.perf_counter() - t0 + + def _capture_all(self) -> None: + import ttnn + + for p in self._programs(): + if p.trace is None: + tid = ttnn.begin_trace_capture(self.device, cq_id=0) + p.out = self._run_program(p) + ttnn.end_trace_capture(self.device, tid, cq_id=0) + p.trace = tid + ttnn.synchronize_device(self.device) + self._captured = True + + def _release_all(self) -> None: + import ttnn + + for p in self._programs(): + if p.trace is not None: + ttnn.release_trace(self.device, p.trace) + p.trace = None + if p.out is not None: + ttnn.deallocate(p.out) + p.out = None + self._captured = False + + def _recompile(self, build, *args): + """Release every trace, build something new (allocations), warm it, recapture everything.""" + log.warning("DepthPro2Device: building %s at run time (all traces are recaptured)", args) + self._release_all() + r = build(*args) + self._warm_all() + self._capture_all() + return r + + def _ensure(self, table: dict, build, shape: StageShape) -> _Program: + key = (shape.frames, shape.hp, shape.wp) + p = table.get(key) + if p is not None and p.trace is not None: + return p + return self._recompile(build, shape) + + def _pick(self, table: dict, build, n: int, h: int, w: int, padded_ok: bool) -> _Program: + """The program for an n-frame call: the smallest compiled T >= n when ``padded_ok``, else exactly n.""" + if padded_ok: + ts = sorted(t for (t, hh, ww) in table if (hh, ww) == (h, w) and t >= n) + if ts: + return self._ensure(table, build, StageShape(ts[0], h, w)) + return self._ensure(table, build, StageShape(n, h, w)) + + # ------------------------------------------------------------------------------------------- run + def _upload(self, p: _Program, patches: torch.Tensor) -> None: + import ttnn + + t0 = time.perf_counter() + host = ttnn.from_torch(patches.to(torch.bfloat16).reshape(1, 1, -1, 768), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT) + t1 = time.perf_counter() + ttnn.copy_host_to_device_tensor(host, p.inp, cq_id=0) + self.last_timing.update(tilize_ms=(t1 - t0) * 1e3, upload_ms=(time.perf_counter() - t1) * 1e3) + + def _run_traced(self, p: _Program, frames: torch.Tensor, before=None): + """unfold -> upload -> (``before()``: runtime inputs) -> replay -> readback (``last_timing``: host ms).""" + import ttnn + + self.last_timing = {} + t0 = time.perf_counter() + t = p.shape.frames + x = frames.float() + if x.shape[0] < t: # runtime valid-frame count: zero frames in the unused slots + x = torch.cat([x, x.new_zeros((t - x.shape[0],) + tuple(x.shape[1:]))]) + patches = unfold_patches(x, p.shape.np_) + self.last_timing["unfold_ms"] = (time.perf_counter() - t0) * 1e3 + self._upload(p, patches) + if before is not None: + before() + t1 = time.perf_counter() + ttnn.execute_trace(self.device, p.trace, cq_id=0, blocking=False) + out = ttnn.to_torch(p.out).float() + self.last_timing["replay_readback_ms"] = (time.perf_counter() - t1) * 1e3 + return out + + def inverse_depth(self, x: torch.Tensor) -> torch.Tensor: + """Normalized, padded frames ``[n, 3, Hp, Wp]`` float32 -> inverse depth ``[n, Hp, Wp]`` float32 (pre-crop). + Runs the smallest compiled T >= n with a runtime valid-frame count n (exactly n-frame semantics).""" + if x.ndim != 4 or x.shape[1] != 3: + raise ValueError(f"expected [T, 3, Hp, Wp], got {tuple(x.shape)}") + n, _, h, w = (int(v) for v in x.shape) + if n < 1: + raise ValueError("inverse_depth: empty clip") + p = self._pick(self._depth, self._build_depth, n, h, w, self.valid_frames) + enc = p.engines[0] + before = (lambda: enc.set_valid_frames(n)) if p.shape.frames > 1 and self.valid_frames else None + return self._run_traced(p, x, before).reshape(p.shape.frames, h, w)[:n] + + def fov_logits(self, y: torch.Tensor) -> torch.Tensor: + """fov_resize'd frames ``[n, 3, h, w]`` float32 -> logits ``[n, 2]`` float32 (frames are independent: the + smallest compiled T >= n runs with zero frames in the unused slots).""" + if not self.has_fov: + raise RuntimeError("DepthPro2Device was created without FOV weights") + if y.ndim != 4 or y.shape[1] != 3: + raise ValueError(f"expected [T, 3, h, w], got {tuple(y.shape)}") + n, _, h, w = (int(v) for v in y.shape) + p = self._pick(self._fov, self._build_fov, n, h, w, True) + return self._run_traced(p, y).reshape(p.shape.frames, 2)[:n] + + # ------------------------------------------------------------------------------------------- unbuffered video + def kv_cache(self, bucket: Tuple[int, int], window: int) -> KVCache: + """Open a key-value cache of the last ``window`` frames (``1 <= window <= max_frames``) for one padded bucket + (one per stream). Step programs of the bucket are built on first use if ``kv_cache=False`` was passed.""" + bucket = (int(bucket[0]), int(bucket[1])) + if bucket not in self.buckets: + raise ValueError(f"kv_cache: {bucket} is not a compiled size {self.buckets}") + if not 1 <= int(window) <= self.max_frames: + raise ValueError(f"kv_cache: window {window} outside 1..{self.max_frames}") + kb = self._kv.get(bucket) + free = [s for s in (kb["slots"] if kb else []) if not s.in_use] + slot = free[0] if free else self._recompile(self._add_kv_slot, bucket) + slot.in_use = True + return KVCache(self, bucket, int(window), slot) + + def _release_kv(self, cache: KVCache) -> None: + cache._slot.in_use = False + + def inverse_depth_step(self, x: torch.Tensor, cache: KVCache) -> torch.Tensor: + """One normalized, padded frame ``[1, 3, Hp, Wp]`` attending the cache -> inverse depth ``[1, Hp, Wp]`` + (``cpu_engine.CPUEngine.inverse_depth_step`` semantics); the frame is added to the cache.""" + if not isinstance(cache, KVCache) or cache._owner is not self: + raise ValueError("inverse_depth_step: the cache must come from this device's kv_cache()") + if cache.closed: + raise RuntimeError("inverse_depth_step: the cache is closed") + if x.ndim != 4 or x.shape[0] != 1 or x.shape[1] != 3: + raise ValueError(f"inverse_depth_step takes one frame (1, 3, H, W), got {tuple(x.shape)}") + if tuple(int(v) for v in x.shape[-2:]) != cache.bucket: + raise ValueError(f"inverse_depth_step: frame {tuple(x.shape[-2:])} != the cache's {cache.bucket}") + kb = self._kv[cache.bucket] + p = cache._slot.program + fill = min(cache.seen + 1, cache.window) + out = self._run_traced(p, x, lambda: kb["enc"].set_fill(fill)) + cache.seen += 1 + return out.reshape(1, *cache.bucket) + + def kv_cache_bytes(self) -> int: + """Device bytes of one cache's ring state for each bucket (the largest).""" + sizes = [s.state.nbytes for kb in self._kv.values() for s in kb["slots"]] + return max(sizes) if sizes else kv_state_bytes(self.size, self.buckets, self.max_frames) + + # ------------------------------------------------------------------------------------------- info + def configurations(self) -> Dict[str, List[Tuple[int, int, int]]]: + return {"depth": sorted(self._depth), "fov": sorted(self._fov), + "kv": [(b, len(kb["slots"])) for b, kb in self._kv.items()]} + + def close(self) -> None: + if getattr(self, "_depth", None) is None: + return + try: + self._release_all() + finally: + for kb in self._kv.values(): + for s in kb["slots"]: + s.state.free() + self._kv.clear() + self._depth.clear() + self._fov.clear() + + +# ----------------------------------------------------------------------------------------------- sizing + +# measured trace bytes of the ttnn engines (logs/depthpro2/baseline/bench.jsonl): ENC base per size (VGA, T=1), +# per fp32-attention query chunk; DEC per frame group = a + b * Mpixels of the group; FOV per (shape, T) +_ENC_BASE_MB = {"S": 7.5, "B": 7.5, "L": 14.5, "H": 21.0} +_FP32_CHUNK_MB = 0.05 +_DEC_GROUP_MB = {"S": (0.9, 0.7), "B": (0.95, 1.4), "L": (0.9, 4.0), "H": (0.9, 4.0)} +_FOV_MB = 8.0 +_STEP_EXTRA_MB = 3.0 + + +def _enc_trace_mb(size: str, t: int, hp: int, wp: int) -> float: + from .ttnn_enc import FP32_ATTN_BLOCKS + + s = StageShape(t, hp, wp) + heads = ref.SIZES[size].heads + budget = 256 << 20 + q_rows = max(32, min(s.lp, budget // (t * heads * s.lp * 4) // 32 * 32)) + chunks = -(-s.lp // q_rows) * len(FP32_ATTN_BLOCKS[size]) + return _ENC_BASE_MB[size] + _FP32_CHUNK_MB * chunks + + +def _dec_trace_mb(size: str, t: int, hp: int, wp: int) -> float: + max_pix = int(os.environ.get("DEPTHPRO2_TTNN_DEC_PIX", str(1 << 21))) + g = max(1, min(t, max_pix // (hp * wp))) + while t % g: + g -= 1 + a, b = _DEC_GROUP_MB[size] + return (t // g) * (a + b * g * hp * wp / 1e6) + + +def trace_region_bytes(size: str, buckets: Sequence[Tuple[int, int]], frames: Sequence[int], engine=None, + fov_shapes: Optional[Sequence[Tuple[int, int]]] = None, kv_cache: bool = False, + kv_streams: int = 1, margin: float = 1.3) -> int: + """Estimated trace-region bytes for a ``DepthPro2Device`` of ``size`` with these padded ``buckets`` and compiled + clip lengths ``frames`` (the T values that get a program: ``max_frames`` and 1 if images are served), ``fov_shapes`` + (default: ``fov_size`` of each bucket; ``[]`` = no FOV) and the unbuffered step programs (``kv_cache``, one per + stream and bucket). From the measured ttnn trace sizes, times ``margin``, plus 32 MiB, rounded up to 32 MiB. + ``mk`` stages are estimated with the ttnn numbers (an upper bound for megakernels).""" + size = _norm_size(size) + frames = sorted({int(t) for t in frames}) + if fov_shapes is None: + fov_shapes = [DepthPro2Device.fov_size(h, w) for h, w in buckets] + mb = 0.0 + for hp, wp in buckets: + for t in frames: + mb += _enc_trace_mb(size, t, hp, wp) + _dec_trace_mb(size, t, hp, wp) + if kv_cache: + mb += kv_streams * (_enc_trace_mb(size, 1, hp, wp) + _dec_trace_mb(size, 1, hp, wp) + _STEP_EXTRA_MB) + for h, w in fov_shapes: + for t in frames: # the FOV trunk is ViT-S: its fp32-attention chunks as for S + mb += _FOV_MB + (_enc_trace_mb("S", t, h, w) - _ENC_BASE_MB["S"]) + total = int(mb * margin * (1 << 20)) + (32 << 20) + return -(-total // (32 << 20)) * (32 << 20) + + +def planned_frames(max_frames: int, frames: Optional[Sequence[int]] = None, clip_lengths=None, engine=None) -> List[int]: + """The T values ``DepthPro2Device`` compiles for these arguments (``trace_region_bytes``' ``frames``): with an ENC + engine that supports a runtime valid-frame count, ``max_frames`` and 1 (if 1 is asked for); else every asked + length.""" + asked = set(range(1, max_frames + 1)) if clip_lengths == "all" else {int(t) for t in (clip_lengths or ())} + asked |= {int(max_frames), *(int(t) for t in (frames or ()))} + enc = engine_class("enc", parse_engine(engine)["enc"]) + if getattr(enc, "supports_valid_frames", False): + return sorted({int(max_frames)} | ({1} if 1 in asked else set())) + return sorted(asked) + + +def kv_state_bytes(size: str, buckets: Sequence[Tuple[int, int]], max_frames: int) -> int: + """Device bytes of ONE unbuffered-video cache (the largest bucket): per cross-frame block K and V of + ``max_frames - 1`` frames (bf16) + their prefix rows (fp32).""" + from . import ceil32 + + cfg = ref.SIZES[_norm_size(size)] + best = 0 + for hp, wp in buckets: + n = (hp // 16) * (wp // 16) + rows = (max_frames - 1) * n + per = 2 * cfg.heads * ceil32(rows) * 64 * 2 + (max_frames - 1) * 32 * cfg.dim * 4 if max_frames > 1 else 0 + best = max(best, per * len(cfg.cross_frame_blocks)) + return best diff --git a/code/tt_depthpro2/tt/ttnn_dec.py b/code/tt_depthpro2/tt/ttnn_dec.py new file mode 100644 index 0000000000000000000000000000000000000000..ee08e92172d9b281ffb70524af2df573739fc6bd --- /dev/null +++ b/code/tt_depthpro2/tt/ttnn_dec.py @@ -0,0 +1,258 @@ +# SPDX-License-Identifier: Apache-2.0 +"""DEC stage, ttnn baseline: per frame reassemble + DPT decoder + head -> inverse depth. + +Stage contract (SPEC §3): + +* ``DEC.in`` the 4 taps ``[1, 1, T * Np, C]`` bf16 TILE DRAM (rows ``>= N`` of each frame ignored). +* ``DEC.out`` ``inv`` ``[T, Hp, Wp]`` **float32 TILE DRAM**, the reference ``inverse_depth`` before the crop + (``head.out[:, 0]``). ``ttnn.to_torch(inv)`` gives ``[T, Hp, Wp]`` directly. + +Feature maps are NHWC rows ``[1, 1, B * H * W, C]`` (bf16 TILE, DRAM interleaved) for a group of ``B`` frames. +3x3 convs = ``ttnn.conv2d`` (auto DRAM slicing), conv-transposes = ``ttnn.conv_transpose2d`` (DRAM height slicing), +1x1 convs = ``ttnn.linear`` on the rows. Conv weights are prepared by the op on the first (warm-up) call and cached +per engine (so per shape). The last 1x1 conv (32 -> 1) runs on the transposed map: ``w^T @ y^T`` -> one float32 row +of ``B * Hp * Wp`` pixels -> ``[B, Hp, Wp]`` (no 32x padded column). + +Frames are decoded in groups of ``B`` frames (``DEPTHPRO2_TTNN_DEC_PIX`` = max pixels per group, default 2^21 = +2.1 M ~ 6 VGA frames or one 1088x1920 frame; full-resolution maps hold ``B * Hp * Wp * max(dim_decoder / 2, 32)`` +bf16 values); ``B`` divides T. + +The group is validated by the first (eager, warm-up) run of the engine: ttnn's conv2d / conv_transpose2d DRAM +slicing picks its slice count from an L1 estimate that does not hold for large batches (L at 256x320, T = 16, group +16: "Statically allocated circular buffers ... clash with L1 buffers", the L1 buffer being the op's own per-slice +input; nothing of ours is resident in L1). When that first run fails with an L1 circular-buffer clash or an L1 +out-of-memory, the engine retries with the next smaller divisor of T (16 -> 8 -> 4 -> 2 -> 1) and keeps the group that +works; later runs (trace capture, replays) use it unchanged. ``DEPTHPRO2_TTNN_DEC_GROUP`` (frames) caps the group. +""" + +from __future__ import annotations + +import gc +import logging +import os +from typing import Dict, List, Optional, Tuple + +import torch + +from ..reference import model as ref +from . import StageShape +from .ttnn_enc import Configs, _ttnn, free_unless_shared, kernel_config, view +from .weights import ConvSpec, DecWeights, MatSpec, dev_tensor, upload_dec + +log = logging.getLogger(__name__) + + +def l1_capacity_error(e: BaseException) -> bool: + """A host-side L1 placement failure of an op (raised before anything is enqueued): CB / L1 buffer clash or L1 OOM.""" + m = str(e) + return "clash with L1 buffers" in m or ("Out of Memory" in m and "L1" in m) + + +class Engine: + """ttnn DEC engine for one :class:`StageShape`: ``run(taps) -> inv [T, Hp, Wp] float32``.""" + + def __init__(self, device, weights, shape: StageShape, size: Optional[str] = None): + ttnn = _ttnn() + if isinstance(weights, dict): + if size is None: + raise ValueError("size is required with host weights") + weights = Engine.prepare_weights(device, weights, size) + self.device = device + self.w: DecWeights = weights + self.shape = shape + self.cfgs = Configs(device) + self.conv_cfg = kernel_config(device, os.environ.get("DEPTHPRO2_TTNN_CONV_FID", "hifi4"), True) + self.mem = ttnn.DRAM_MEMORY_CONFIG + self.relu = ttnn.UnaryWithParam(ttnn.UnaryOpType.RELU) + self.prepared: Dict[int, Tuple[object, object]] = {} + T = shape.frames + # 2^21: a 1088x1920 frame decodes alone (2 frames per group at that size: conv2d static CBs clash with an L1 + # buffer for dim_decoder 256, L / H) + max_pix = int(os.environ.get("DEPTHPRO2_TTNN_DEC_PIX", str(1 << 21))) + self.group = max(1, min(T, max_pix // (shape.hp * shape.wp), int(os.environ.get("DEPTHPRO2_TTNN_DEC_GROUP", "16")))) + while T % self.group: + self.group -= 1 + self.group_checked = False # set by the first successful run (see the module doc) + # last 1x1 conv: row 0 of a [32, 32] tile holds the weights + wr = torch.zeros(1, 1, 32, 32) + wr[0, 0, 0] = self.w.head4_w + self.head4_row = view(dev_tensor(wr, device), [1, 1, 1, 32], [1, 1, 32, 32]) + self.slice_cfg = ttnn.Conv2dSliceConfig(slice_type=ttnn.Conv2dDRAMSliceHeight, num_slices=0) + + @staticmethod + def prepare_weights(device, host_weights, size: str) -> DecWeights: + # reassemble.0.1 (k4s4 conv-transpose) runs as ttnn.conv_transpose2d (no stock tile-friendly depth-to-space) + return upload_dec(device, host_weights, ref.SIZES[size], convt4_matmul=False) + + # -- pieces + def _conv(self, x, spec: ConvSpec, b: int, h: int, w: int, act: bool = False): + ttnn = _ttnn() + # config tensors in DRAM: they live as long as the cached program, and the 32 KB L1_SMALL per core fills up + # after one shape's decoder (a second bucket / T then fails with an L1_SMALL OOM) + cc = ttnn.Conv2dConfig(weights_dtype=ttnn.bfloat16, activation=self.relu if act else None, + output_layout=ttnn.TILE_LAYOUT, config_tensors_in_dram=True) + wt, bt = self.prepared.get(id(spec), (spec.w_host, spec.b_host)) + common = dict(input_tensor=x, weight_tensor=wt, bias_tensor=bt, device=self.device, in_channels=spec.cin, + out_channels=spec.cout, batch_size=b, input_height=h, input_width=w, kernel_size=(spec.k, spec.k), + stride=(spec.stride, spec.stride), padding=(spec.pad, spec.pad), dilation=(1, 1), groups=1, + conv_config=cc, compute_config=self.conv_cfg, dtype=ttnn.bfloat16, memory_config=self.mem, + return_output_dim=True, return_weights_and_bias=True) + if spec.transpose: + y, (ho, wo), (pw, pb) = ttnn.conv_transpose2d(output_padding=(0, 0), dram_slice_config=self.slice_cfg, **common) + else: + y, (ho, wo), (pw, pb) = ttnn.conv2d(**common) + self.prepared[id(spec)] = (pw, pb) + if y.layout != ttnn.TILE_LAYOUT: + y2 = ttnn.to_layout(y, ttnn.TILE_LAYOUT, memory_config=self.mem) + ttnn.deallocate(y) + y = y2 + if y.is_sharded(): + y2 = ttnn.sharded_to_interleaved(y, self.mem) + ttnn.deallocate(y) + y = y2 + return y, ho, wo + + def _mm(self, x, spec: MatSpec): + ttnn = _ttnn() + return ttnn.linear(x, spec.w, bias=spec.b, memory_config=self.mem, dtype=ttnn.bfloat16, compute_kernel_config=self.cfgs.mm) + + def _residual(self, x, key: str, b: int, h: int, w: int): + ttnn = _ttnn() + r = ttnn.relu(x, memory_config=self.mem) + y, _, _ = self._conv(r, self.w.res[key + ".c1"], b, h, w, act=True) + ttnn.deallocate(r) + y2, _, _ = self._conv(y, self.w.res[key + ".c3"], b, h, w) + ttnn.deallocate(y) + out = ttnn.add(x, y2, memory_config=self.mem) + ttnn.deallocate(y2) + return out + + def _fusion(self, x, i: int, skip, b: int, h: int, w: int): + ttnn = _ttnn() + if skip is not None: + r = self._residual(skip, f"f{i}.r1", b, h, w) + x2 = ttnn.add(x, r, memory_config=self.mem) + ttnn.deallocate(r) + ttnn.deallocate(x) + x = x2 + y = self._residual(x, f"f{i}.r2", b, h, w) + ttnn.deallocate(x) + d, h2, w2 = self._conv(y, self.w.deconv[i], b, h, w) + ttnn.deallocate(y) + o = self._mm(d, self.w.out_conv[i]) + ttnn.deallocate(d) + return o, h2, w2 + + def _nhwc(self, tap, b: int, i: int): + """tap rows [1, 1, b * Np, C] -> reassemble.i.0 (1x1) -> NHWC rows [1, 1, b * N, d_i].""" + ttnn = _ttnn() + s = self.shape + y = self._mm(tap, self.w.reassemble_mm[i]) + d = self.w.reassemble_mm[i].cout + if s.n == s.np_: + return y + if b == 1: + return view(y, [1, 1, s.n, d], [1, 1, s.np_, d]) + z = ttnn.reshape(view(y, [b, 1, s.n, d], [b, 1, s.np_, d]), [1, 1, b * s.n, d], memory_config=self.mem) + free_unless_shared(y, z) + return z + + def _pyramid(self, taps, b: int): + s = self.shape + gh, gw = s.gh, s.gw + out = [] + for i in range(4): + x = self._nhwc(taps[i], b, i) + if i in (0, 1): + y, h, w = self._conv(x, self.w.reassemble_up[i], b, gh, gw) + _ttnn().deallocate(x) + elif i == 3: + y, h, w = self._conv(x, self.w.reassemble_up[3], b, gh, gw) + _ttnn().deallocate(x) + else: + y, h, w = x, gh, gw + out.append((y, h, w)) + return out + + def _final(self, x, b: int): + """head.4 (1x1, 32 -> 1) + ReLU on NHWC rows [1, 1, P, 32] -> float32 [b, Hp, Wp].""" + ttnn = _ttnn() + s = self.shape + xt = ttnn.transpose(x, -2, -1, memory_config=self.mem) # [1, 1, 32, P] + z = ttnn.matmul(self.head4_row, xt, memory_config=self.mem, dtype=ttnn.float32, compute_kernel_config=self.cfgs.mm) + ttnn.deallocate(xt) + z2 = ttnn.relu(ttnn.add(z, self.w.head4_b, memory_config=self.mem), memory_config=self.mem) + ttnn.deallocate(z) + out = ttnn.reshape(z2, [b, s.hp, s.wp], memory_config=self.mem) + free_unless_shared(z2, out) + return out + + def decode(self, taps, b: int): + """``taps``: 4 x [1, 1, b * Np, C] -> float32 [b, Hp, Wp].""" + ttnn = _ttnn() + pyr = self._pyramid(taps, b) + (p3, h3, w3) = pyr[3] + x, _, _ = self._conv(p3, self.w.convs[3], b, h3, w3) + ttnn.deallocate(p3) + x, h, w = self._fusion(x, 3, None, b, h3, w3) + for i in (2, 1, 0): + (pi, hi, wi) = pyr[i] + skip, _, _ = self._conv(pi, self.w.convs[i], b, hi, wi) + ttnn.deallocate(pi) + assert (h, w) == (hi, wi), f"fusion {i}: {(h, w)} vs {(hi, wi)}" + x, h, w = self._fusion(x, i, skip, b, hi, wi) + ttnn.deallocate(skip) + # head at 1/2 then 1/1 + y, h, w = self._conv(x, self.w.head0, b, h, w) + ttnn.deallocate(x) + y2, h, w = self._conv(y, self.w.head1, b, h, w) + ttnn.deallocate(y) + y3, h, w = self._conv(y2, self.w.head2, b, h, w, act=True) + ttnn.deallocate(y2) + assert (h, w) == (self.shape.hp, self.shape.wp) + out = self._final(y3, b) + ttnn.deallocate(y3) + return out + + def run(self, taps) -> object: + if self.group_checked: + return self._run(taps) + while True: + err = None + try: + out = self._run(taps) + except RuntimeError as e: + if self.group == 1 or not l1_capacity_error(e): + raise + err = str(e).split("info:")[-1].strip().splitlines()[0][:200] + if err is None: + self.group_checked = True + return out + # the failed attempt's tensors die with its traceback (outside the except block) + gc.collect() + g = self.group - 1 + while self.shape.frames % g: + g -= 1 + log.warning("ttnn DEC %s: frame group %d does not fit in L1 (%s); retrying with group %d", + self.shape, self.group, err, g) + self.group = g + self.prepared.clear() # prepared conv weights depend on the batch (shard / block config) + + def _run(self, taps) -> object: + ttnn = _ttnn() + s = self.shape + T, g = s.frames, self.group + if g == T: + return self.decode(taps, T) + outs = [] + rows = g * s.np_ + for f0 in range(0, T, g): + part = [ttnn.slice(t, [0, 0, f0 * s.np_, 0], [1, 1, f0 * s.np_ + rows, t.shape[-1]], memory_config=self.mem) + for t in taps] + outs.append(self.decode(part, g)) + for p in part: + ttnn.deallocate(p) + out = ttnn.concat(outs, dim=0, memory_config=self.mem) + for o in outs: + ttnn.deallocate(o) + return out diff --git a/code/tt_depthpro2/tt/ttnn_enc.py b/code/tt_depthpro2/tt/ttnn_enc.py new file mode 100644 index 0000000000000000000000000000000000000000..77ef3173dba5062bf225db53287d15ec1a87c7fb --- /dev/null +++ b/code/tt_depthpro2/tt/ttnn_enc.py @@ -0,0 +1,653 @@ +# SPDX-License-Identifier: Apache-2.0 +"""ENC stage, ttnn baseline: patch embedding + prefix + every DINOv3 block (within-frame / cross-frame) -> 4 taps. + +Stage contract (SPEC §3): + +* ``ENC.in`` ``patches`` ``[1, 1, T * Np, 768]`` bf16 TILE DRAM, rows ``>= N`` of each frame zero + (host: ``tt.weights.unfold_patches``; columns in ``(c, ky, kx)`` order). +* ``ENC.out`` ``taps[i]`` ``[1, 1, T * Np, C]`` bf16 TILE DRAM, raster order of the grid, rows ``>= N`` of each frame + are garbage (here: the prefix tokens and finite padding). + +Internal token layout (ttnn engine only): ``X`` ``[T, 1, Lp, C]`` with, per frame, rows ``[0, N)`` = patch tokens, +rows ``[N, N + 5)`` = cls + 4 registers, rows ``[N + 5, Lp)`` = finite padding, ``Lp = ceil32(N + 5)``. Attention is +order-invariant (RoPE is applied per row from a table whose prefix / padding rows are the identity), so a within-frame +block is one plain SDPA over the logical ``N + 5`` rows; the op masks the padded keys itself. + +Cross-frame block, ``T > 1``: the joint sequence ``[pooled prefix (5) ; patches of frames 0..T-1 (T * N)]`` (patch +rows compacted with a tiled ``ttnn.reshape``, the pooled prefix concatenated in front) runs through ONE windowed +``ttnn.transformer.scaled_dot_product_attention`` (``cu_window_seqlens``); each frame's own prefix rows are carried +over unchanged. ``T == 1``: the joint sequence equals the frame's own sequence, so the block is a within-frame block +whose prefix-row updates are masked out. + +Runtime valid-frame count (one T-frame program serves any n-frame clip, ``1 <= n <= T``): the host puts the n frames +in frame slots ``[0, n)`` (slots ``>= n``: zero patches) and calls ``Engine.set_valid_frames(n)`` before the run / +trace replay. Two persistent device tensors carry ``n`` (written with ``ttnn.copy_host_to_device_tensor``): + +* ``vf_cu`` int32 ROW_MAJOR DRAM, shape ``[3]`` = ``[0, 5 + n * N, 5 + T * N]``: window 0 = pooled prefix + frames + ``< n`` (the clip's joint keys / queries), window 1 = frames ``>= n`` (they only see each other: don't-care); +* ``vf_w`` float32 TILE DRAM, shape ``[T, 1, 1, 1]`` = ``1 / n`` for ``t < n`` else 0: pooled prefix = + ``sum_t vf_w[t] * prefix_t``. + +Within-frame blocks need nothing (frames are independent); taps / outputs of frames ``>= n`` are don't-care. + +The same :class:`Trunk` runs the FOV trunk (``joint_cross=False``: blocks 5/7/9/11 freeze the prefix, no joint +attention; taps include the prefix rows). +""" + +from __future__ import annotations + +import os +from typing import Dict, List, Optional, Sequence, Tuple + +import torch + +from ..reference import model as ref +from . import NUM_PREFIX, StageShape, ceil32 +from .weights import BlockWeights, TrunkWeights, dev_tensor, upload_trunk + +HEAD_DIM = 64 + +#: Blocks whose attention logits reach 1e4..3e6 (|q|, |k| ~ 1e3 with a hard, RoPE-positional attention pattern; host scan +#: of every golden input, logs/depthpro2/baseline/BASELINE.md). The stock flash SDPA keeps its running row max in bf16 +#: (ulp 2^-8 relative), so exp() overflows there (block 0 of S: PCC 0.36). These blocks run an fp32-score attention +#: (QK^T in fp32, fp32 softmax, bf16 P @ V), chunked over query rows. The max logit of every other block is < 700. +FP32_ATTN_BLOCKS = {"S": (0,), "B": (0,), "L": (1,), "H": (0, 1), "fov": (0,)} + + +def fp32_attn_blocks(key: str) -> Tuple[int, ...]: + """``DEPTHPRO2_TTNN_FP32_ATTN`` = ``auto`` (table above) | ``none`` | ``all`` | comma list of block indices.""" + o = _env("DEPTHPRO2_TTNN_FP32_ATTN", "auto") + if o == "auto": + return FP32_ATTN_BLOCKS[key] + if o == "none": + return () + if o == "all": + return tuple(range(64)) + return tuple(int(v) for v in o.split(",") if v.strip()) + + +# ----------------------------------------------------------------------------------------------- shared ttnn helpers + + +def _ttnn(): + import ttnn + + return ttnn + + +def _env(name: str, default: str) -> str: + return os.environ.get(name, default) + + +def kernel_config(device, fidelity: str = "hifi4", fp32_acc: bool = True, approx: bool = False): + ttnn = _ttnn() + fid = {"hifi4": ttnn.MathFidelity.HiFi4, "hifi3": ttnn.MathFidelity.HiFi3, "hifi2": ttnn.MathFidelity.HiFi2, + "lofi": ttnn.MathFidelity.LoFi}[fidelity] + return ttnn.init_device_compute_kernel_config(device.arch(), math_fidelity=fid, math_approx_mode=approx, + fp32_dest_acc_en=fp32_acc, packer_l1_acc=True) + + +def view(t, logical: Sequence[int], padded: Optional[Sequence[int]] = None): + """Logical-shape view of a TILE tensor (same buffer). ``padded`` defaults to the tensor's padded shape.""" + ttnn = _ttnn() + padded = list(padded) if padded is not None else list(t.padded_shape) + padded[-1] = ceil32(padded[-1]) # TILE: the last dim is always padded to the tile width + return ttnn.reshape(t, ttnn.Shape(list(logical)), ttnn.Shape(padded)) + + +def full_view(t): + """View with logical shape == padded shape.""" + return view(t, list(t.padded_shape)) + + +def same_buffer(a, b) -> bool: + """True if ``a`` and ``b`` share a device buffer (``ttnn.reshape`` returns a view for tile-aligned reshapes: + deallocating the source would free the view's memory).""" + try: + return a.buffer_address() == b.buffer_address() + except Exception: # noqa: BLE001 + return a is b + + +def free_unless_shared(src, dst) -> None: + """Deallocate ``src`` unless ``dst`` is a view of it.""" + if not same_buffer(src, dst): + _ttnn().deallocate(src) + + +def sdpa_chunks(sq: int, sk: int, joint: int = 0) -> Tuple[int, int]: + """(q_chunk, k_chunk) for an SDPA over ``sq`` queries / ``sk`` keys (+ ``joint`` keys of a joint SDPA, which the op + pads to a whole k chunk). The largest k chunk in {1024, 512, 256, 128} whose padding stays within 15 % (fewer + online-softmax rescales of the bf16 partial output: S block-4 attention rel. error 3.8e-3 at k256, 2.9e-3 at + k1024), else the least padding. ``DEPTHPRO2_TTNN_SDPA_CHUNKS=q,k`` overrides.""" + o = _env("DEPTHPRO2_TTNN_SDPA_CHUNKS", "") + if o: + q, k = (int(v) for v in o.split(",")) + return q, k + + def padded(k): + return -(-sk // k) * k + (k if joint else 0) + + need = sk + joint + for k in (1024, 512, 256, 128): + if padded(k) <= 1.15 * need: + return 64, k + return 64, min((1024, 512, 256, 128), key=lambda k: (padded(k), -k)) + + +class Configs: + """Compute-kernel configs of the baseline (accuracy first: HiFi4 + fp32 accumulation; env knobs for A/B).""" + + def __init__(self, device): + self.mm = kernel_config(device, _env("DEPTHPRO2_TTNN_MM_FID", "hifi4"), True) + self.ln = kernel_config(device, "hifi4", True) + self.sdpa = kernel_config(device, _env("DEPTHPRO2_TTNN_SDPA_FID", "hifi4"), _env("DEPTHPRO2_TTNN_SDPA_FP32", "1") == "1") + self.eltwise = kernel_config(device, "hifi4", True) + self.grid = device.compute_with_storage_grid_size() + # DEPTHPRO2_TTNN_MM=minimal: trunk linears through ttnn.experimental.minimal_matmul (A/B knob) + self.minimal = None + if _env("DEPTHPRO2_TTNN_MM", "linear") == "minimal": + import ttnn + + m, k, n, sh, sw = (int(v) for v in _env("DEPTHPRO2_TTNN_MM_BLOCKS", "8,4,4,1,4").split(",")) + self.minimal = ttnn.MinimalMatmulConfig(M_block_size=m, K_block_size=k, N_block_size=n, subblock_h=sh, + subblock_w=sw, compute_with_storage_grid_size=self.grid) + + def sdpa_program(self, sq: int, sk: int, joint: int = 0): + ttnn = _ttnn() + q, k = sdpa_chunks(sq, sk, joint) + return ttnn.SDPAProgramConfig(compute_with_storage_grid_size=self.grid, q_chunk_size=q, k_chunk_size=k, + exp_approx_mode=False) + + +#: SDPA mode. The plain (non-windowed) non-causal ttnn SDPA forwards K/V between the cores of a head ("KV chain +#: forwarding", sdpa_program_factory.cpp) and returns garbage (inf, or PCC 0.97-0.99 / ~0) for some heads with many +#: (q_chunk, k_chunk, batch, heads, S) combinations once batch x heads is large: q64/k256 at S = 1205 (480x640) with +#: B x heads = 80 (4 x 20), 96 (16 x 6, S at T = 16: inverse depth 5e35), 320 (16 x 20), 96 (1 x 96); q128/k512 at +#: 4 x 20; q64/k128 at 16 x 6, S = 773. The windowed program (``cu_window_seqlens``) never builds those chains, so it is +#: used whenever batch x heads > ``SDPA_PLAIN_MAX``, with one window over the whole sequence. Up to 24 (every T = 1 +#: program: heads 6 / 12 / 16 / 20, FOV 6; S 256x320 T = 4) the plain op was correct in every probe (S 325 .. 8165, +#: q 64 / 128 / 256, k 128 .. 1024, per-head PCC > 0.9999) and is 1.3-2.2x faster (K/V forwarding: 0.15 vs 0.34 ms at +#: 1 x 6 x 1205). ``DEPTHPRO2_TTNN_SDPA_WINDOWED=0`` = plain everywhere (A/B only: wrong at T = 16), +#: ``DEPTHPRO2_TTNN_SDPA_PLAIN_MAX=0`` = windowed everywhere. +SDPA_WINDOWED = os.environ.get("DEPTHPRO2_TTNN_SDPA_WINDOWED", "1") == "1" +SDPA_PLAIN_MAX = int(os.environ.get("DEPTHPRO2_TTNN_SDPA_PLAIN_MAX", "24")) + + +def sdpa_windowed(batch: int, heads: int) -> bool: + """Whether an SDPA over ``batch`` x ``heads`` (q, k, v [batch, heads, S, d]) must run windowed (see SDPA_WINDOWED).""" + return SDPA_WINDOWED and batch * heads > SDPA_PLAIN_MAX + + +def valid_frame_cu(T: int, n: int, n_patches: int) -> torch.Tensor: + """``vf_cu`` (int32, 3 values): window boundaries of the joint sequence ``[pooled prefix (5) ; T x N patches]``: + window 0 = the pooled prefix and the first ``n`` frames (the clip), window 1 = frames ``n..T-1`` (masked out).""" + s = NUM_PREFIX + T * n_patches + return torch.tensor([0, NUM_PREFIX + n * n_patches, s], dtype=torch.int32) + + +def valid_frame_weights(T: int, n: int) -> torch.Tensor: + """``vf_w`` (float32 ``[T, 1, 1, 1]``): pooled-prefix weight of each frame, ``1 / n`` for ``t < n`` else 0.""" + w = torch.zeros(T, 1, 1, 1) + w[:n] = 1.0 / n + return w + + +def exact_layer_norm(x, w, b, eps: float, mem, cfg): + """LayerNorm in float32 from elementwise / reduction ops (mean, x - mean, mean of squares, rsqrt): float32-exact + (rms rel. 7e-8 on DINOv3 block inputs). ``ttnn.layer_norm`` (HiFi4, fp32 acc) has a per-row scale error of + -1.8e-4 +- 3.3e-4 (BASELINE.md §4), which moves the global depth scale of sensitive images. ``w`` / ``b``: [1, C].""" + ttnn = _ttnn() + x32 = x if x.dtype == ttnn.float32 else ttnn.typecast(x, ttnn.float32, memory_config=mem) + mu = ttnn.mean(x32, dim=-1, keepdim=True, memory_config=mem, compute_kernel_config=cfg) + xc = ttnn.subtract(x32, mu, memory_config=mem) + ttnn.deallocate(mu) + if x32 is not x: + ttnn.deallocate(x32) + sq = ttnn.multiply(xc, xc, memory_config=mem) + var = ttnn.mean(sq, dim=-1, keepdim=True, memory_config=mem, compute_kernel_config=cfg) + ttnn.deallocate(sq) + ve = ttnn.add(var, eps, memory_config=mem) + ttnn.deallocate(var) + rs = ttnn.rsqrt(ve, memory_config=mem) + ttnn.deallocate(ve) + xn = ttnn.multiply(xc, rs, memory_config=mem) + ttnn.deallocate(xc) + ttnn.deallocate(rs) + if w is None: + return xn + y = ttnn.multiply(xn, w, memory_config=mem) + ttnn.deallocate(xn) + if b is None: + return y + out = ttnn.add(y, b, memory_config=mem) + ttnn.deallocate(y) + return out + + +def rope_rows(gh: int, gw: int, rows: int, repeat: int = 1, offset: int = 0) -> Tuple[torch.Tensor, torch.Tensor]: + """cos / sin tables ``[1, 1, rows, 64]``: the reference ``rope_table`` repeated ``repeat`` times from row + ``offset``, the identity (cos 1, sin 0) on every other row (prefix tokens and padding).""" + sin, cos = ref.rope_table(gh, gw) + n = sin.shape[0] * repeat + c = torch.ones(rows, HEAD_DIM) + s = torch.zeros(rows, HEAD_DIM) + c[offset:offset + n] = cos.repeat(repeat, 1) + s[offset:offset + n] = sin.repeat(repeat, 1) + return c.reshape(1, 1, rows, HEAD_DIM), s.reshape(1, 1, rows, HEAD_DIM) + + +# ----------------------------------------------------------------------------------------------- trunk + + +class Trunk: + """A DINOv3 trunk on one :class:`StageShape` (T frames of ``gh x gw`` patches). + + ``run(patches)`` -> the token tensors ``X`` ``[T, 1, Lp, C]`` after each tap block (see module doc).""" + + def __init__(self, device, tw: TrunkWeights, shape: StageShape, *, joint_cross: bool, tap_blocks: Sequence[int], + cross_blocks: Sequence[int], fp32_blocks: Sequence[int] = (), cfgs: Optional[Configs] = None): + ttnn = _ttnn() + self.device = device + self.tw = tw + self.cfg = tw.cfg + self.shape = shape + self.joint_cross = joint_cross + self.tap_blocks = tuple(tap_blocks) + self.cross_blocks = set(cross_blocks) + self.fp32_blocks = set(fp32_blocks) + if joint_cross and shape.frames > 1 and self.fp32_blocks & self.cross_blocks: + raise NotImplementedError(f"fp32 attention in a joint cross-frame block: {sorted(self.fp32_blocks & self.cross_blocks)}") + self.c = self.cfg.dim + self.heads = self.cfg.heads + self.cfgs = cfgs or Configs(device) + T, n, np_, lp = shape.frames, shape.n, shape.np_, shape.lp + self.T, self.n, self.np_, self.lp = T, n, np_, lp + self.mem = ttnn.DRAM_MEMORY_CONFIG + self.act_dtype = ttnn.bfloat16 + # precision knob (DEPTHPRO2_TTNN_PREC): "bf16" = bf16 residual stream and activations; "fp32res" = fp32 residual + # stream (LN reads fp32); "fp32act" = fp32 residual + fp32 proj / fc1 / fc2 outputs (q / k / v stay bf16) + # default fp32act: local per-block error 1.24x the official bf16-autocast run's (bf16: ~1.6x); see BASELINE.md + prec = _env("DEPTHPRO2_TTNN_PREC", "fp32act") + self.prec = prec + self.resid_dtype = ttnn.float32 if prec in ("fp32res", "fp32act") else ttnn.bfloat16 + self.branch_dtype = ttnn.float32 if prec == "fp32act" else ttnn.bfloat16 + # DEPTHPRO2_TTNN_LN = exact (default: fp32 LayerNorm from eltwise / reduction ops) | op (ttnn.layer_norm) + self.ln_exact = _env("DEPTHPRO2_TTNN_LN", "exact") == "exact" + c = self.c + # row constant added to the bias-less patch matmul: rows < N: patch-embed bias; N..N+4: cls + registers; rest 0 + e = torch.zeros(1, 1, lp, c) + e[0, 0, :n] = tw.pe_b_host + e[0, 0, n:n + NUM_PREFIX] = tw.prefix_host + self.embed_rows = dev_tensor(e, device, dtype=self.resid_dtype) + self.pad_rows = dev_tensor(torch.zeros(T, 1, lp - np_, 768), device) if lp > np_ else None + cos, sin = rope_rows(shape.gh, shape.gw, lp) + # RoPE (DEPTHPRO2_TTNN_ROPE): "eltwise" (default) = q * cos + swap_halves(q) * sin_signed with float32 tables + # and float32 math on the bf16 q / k, one bf16 rounding at the end (what torch autocast does); + # "op" = ttnn.experimental.rotary_embedding with bf16 tables; "op32" = the same op on fp32 qkv / tables. + # The bf16 op shifts the global depth scale of sensitive images by ~2 % per block (systematic per-position + # error of the rounded tables; logits up to ~500): BASELINE.md §4. + self.rope_mode = _env("DEPTHPRO2_TTNN_ROPE", "op32" if _env("DEPTHPRO2_TTNN_ROPE32", "0") == "1" else "eltwise") + self.rope32 = self.rope_mode == "op32" + self.tables = {} + self.tables32 = {} + self.add_rope_table("frame", cos, sin) + # patch-row mask (1 on rows < N): freezes the prefix rows (T == 1 cross-frame block, FOV prefix freeze) + m = torch.zeros(1, 1, lp, 1) + m[0, 0, :n] = 1.0 + self.patch_mask = dev_tensor(m, device, dtype=self.resid_dtype) + self.cross_compact = joint_cross and T > 1 + if self.cross_compact: + # joint sequence of a cross-frame block: [pooled prefix (5) ; patches of frames 0..T-1 (T * N)] + self.s_joint = NUM_PREFIX + T * n + cos_t, sin_t = rope_rows(shape.gh, shape.gw, ceil32(self.s_joint), repeat=T, offset=NUM_PREFIX) + self.add_rope_table("clip", cos_t, sin_t) + # runtime valid-frame count (set_valid_frames): windowed SDPA boundaries and pooled-prefix weights + self.vf_cu = self._dev_cu(valid_frame_cu(T, T, n)) + self.vf_w = dev_tensor(valid_frame_weights(T, T), device, dtype=ttnn.float32) + self.valid_frames = T + self.hook = None # debug: hook(block_index, x) after every block (eager runs only) + # within-frame SDPA [T, heads, N + 5]: windowed (one window = the frame's N + 5 tokens) above SDPA_PLAIN_MAX + self.wf_cu = self._dev_cu(torch.tensor([0, n + NUM_PREFIX], dtype=torch.int32)) if sdpa_windowed(T, self.heads) else None + self.sdpa_pc = self.cfgs.sdpa_program(n + NUM_PREFIX, n + NUM_PREFIX) + # fp32-score attention: query rows per chunk so that one [T, H, rows, Lp] fp32 score tensor stays under the budget + budget = int(_env("DEPTHPRO2_TTNN_ATTN_BYTES", str(256 << 20))) + self.q_rows = max(32, min(lp, budget // (T * self.heads * lp * 4) // 32 * 32)) + self.win_pc = self.cfgs.sdpa_program(self.s_joint, self.s_joint) if self.cross_compact else None + + # -- constants / runtime inputs + def add_rope_table(self, name: str, cos: torch.Tensor, sin: torch.Tensor) -> None: + """Register RoPE tables ``[1, 1, rows, 64]`` (bf16 for the ``op`` mode, fp32 / signed sin for ``eltwise``).""" + ttnn = _ttnn() + if self.rope_mode == "op": + self.tables[name] = (dev_tensor(cos, self.device), dev_tensor(sin, self.device)) + elif self.rope32: + self.tables32[name] = (dev_tensor(cos, self.device, dtype=ttnn.float32), dev_tensor(sin, self.device, dtype=ttnn.float32)) + elif self.rope_mode == "eltwise": + sin_signed = torch.cat([-sin[..., :HEAD_DIM // 2], sin[..., HEAD_DIM // 2:]], dim=-1) + self.tables32[name] = (dev_tensor(cos, self.device, dtype=ttnn.float32), + dev_tensor(sin_signed, self.device, dtype=ttnn.float32)) + + def _dev_cu(self, cu: torch.Tensor): + ttnn = _ttnn() + return ttnn.to_device(ttnn.from_torch(cu, dtype=ttnn.int32, layout=ttnn.ROW_MAJOR_LAYOUT), self.device, + memory_config=ttnn.DRAM_MEMORY_CONFIG) + + def set_valid_frames(self, n: int) -> None: + """Host call before a run / trace replay: frames ``[0, n)`` of the T-frame input form the clip (see the module + doc, "Runtime valid-frame count"). Writes ``vf_cu`` / ``vf_w`` in place (no allocation, no compile).""" + ttnn = _ttnn() + T = self.T + if not 1 <= n <= T: + raise ValueError(f"valid frames {n} outside 1..{T}") + if not self.cross_compact: + return + ttnn.copy_host_to_device_tensor(ttnn.from_torch(valid_frame_cu(T, n, self.n), dtype=ttnn.int32, + layout=ttnn.ROW_MAJOR_LAYOUT), self.vf_cu, cq_id=0) + ttnn.copy_host_to_device_tensor(ttnn.from_torch(valid_frame_weights(T, n), dtype=ttnn.float32, + layout=ttnn.TILE_LAYOUT), self.vf_w, cq_id=0) + self.valid_frames = n + + # -- pieces + def _ln(self, x, w, b): + ttnn = _ttnn() + if self.ln_exact: + return exact_layer_norm(x, w, b, ref.LN_EPS, self.mem, self.cfgs.ln) + return ttnn.layer_norm(x, epsilon=ref.LN_EPS, weight=w, bias=b, memory_config=self.mem, + compute_kernel_config=self.cfgs.ln) + + def _lin(self, x, w, b=None, act=None, dtype=None): + ttnn = _ttnn() + if self.cfgs.minimal is not None and x.dtype == w.dtype: + fa = None + if act == "gelu": + fa = ttnn.UnaryWithParam(ttnn.UnaryOpType.GELU, 0.0) + elif act == "silu": + fa = ttnn.UnaryWithParam(ttnn.UnaryOpType.SILU) + return ttnn.experimental.minimal_matmul(x, w, bias_tensor=b, fused_activation=fa, config=self.cfgs.minimal, + memory_config=self.mem, dtype=dtype or self.act_dtype, + compute_kernel_config=self.cfgs.mm) + return ttnn.linear(x, w, bias=b, activation=act, memory_config=self.mem, dtype=dtype or self.act_dtype, + compute_kernel_config=self.cfgs.mm) + + def _mlp(self, h, bw: BlockWeights): + ttnn = _ttnn() + bd = self.branch_dtype + if self.cfg.swiglu: + g = self._lin(h, bw.fcg_w, bw.fcg_b, act="silu", dtype=bd) + u = self._lin(h, bw.fcx_w, bw.fcx_b, dtype=bd) + m = ttnn.multiply(g, u, memory_config=self.mem) + ttnn.deallocate(g) + ttnn.deallocate(u) + else: + m = self._lin(h, bw.fc1_w, bw.fc1_b, act="gelu", dtype=bd) + f = self._lin(m, bw.fc2_w, bw.fc2_b, dtype=bd) + ttnn.deallocate(m) + return f + + def _rope_eltwise(self, x, cos, sin_signed): + """x * cos + [x2, x1] * [-sin, sin] in float32 (x bf16 [B, H, R, 64]) -> bf16 (one RNE rounding).""" + ttnn = _ttnn() + xf = full_view(x) + b, h, r = xf.padded_shape[0], xf.padded_shape[1], xf.padded_shape[2] + half = HEAD_DIM // 2 + x1 = ttnn.slice(xf, [0, 0, 0, 0], [b, h, r, half], memory_config=self.mem) + x2 = ttnn.slice(xf, [0, 0, 0, half], [b, h, r, HEAD_DIM], memory_config=self.mem) + sw = ttnn.concat([x2, x1], dim=-1, memory_config=self.mem) + ttnn.deallocate(x1) + ttnn.deallocate(x2) + a = ttnn.multiply(xf, cos, dtype=ttnn.float32, memory_config=self.mem) + c = ttnn.multiply(sw, sin_signed, dtype=ttnn.float32, memory_config=self.mem) + ttnn.deallocate(sw) + s = ttnn.add(a, c, dtype=ttnn.float32, memory_config=self.mem) + ttnn.deallocate(a) + ttnn.deallocate(c) + out = ttnn.typecast(s, ttnn.bfloat16, memory_config=self.mem) + ttnn.deallocate(s) + return out + + def _qkv(self, h, bw: BlockWeights): + return self._lin(h, bw.qkv_w, bw.qkv_b, dtype=_ttnn().float32 if self.rope32 else None) + + def _heads(self, qkv, rows: int, rows_p: int, batch: int, table: Optional[str] = None): + """[B, 1, rows_p, 3C] -> q, k, v [B, H, rows (logical), 64] bf16 (RoPE table ``frame`` / ``clip`` on q / k).""" + ttnn = _ttnn() + q, k, v = ttnn.experimental.nlp_create_qkv_heads(qkv, num_heads=self.heads, num_kv_heads=self.heads, + transpose_k_heads=False, memory_config=self.mem) + f32 = qkv.dtype == ttnn.float32 + if table is not None and self.rope_mode == "eltwise": + cos, sin_s = self.tables32[table] + q2, k2 = self._rope_eltwise(q, cos, sin_s), self._rope_eltwise(k, cos, sin_s) + ttnn.deallocate(q) + ttnn.deallocate(k) + q, k = q2, k2 + elif table is not None: + cos, sin = (self.tables32 if f32 else self.tables)[table] + q2 = ttnn.experimental.rotary_embedding(q, cos, sin, memory_config=self.mem, compute_kernel_config=self.cfgs.eltwise) + k2 = ttnn.experimental.rotary_embedding(k, cos, sin, memory_config=self.mem, compute_kernel_config=self.cfgs.eltwise) + ttnn.deallocate(q) + ttnn.deallocate(k) + q, k = q2, k2 + if f32: + outs = [] + for a in (q, k, v): + outs.append(ttnn.typecast(a, ttnn.bfloat16, memory_config=self.mem)) + ttnn.deallocate(a) + q, k, v = outs + shp = [batch, self.heads, rows, HEAD_DIM] + pad = [batch, self.heads, rows_p, HEAD_DIM] + return view(q, shp, pad), view(k, shp, pad), view(v, shp, pad) + + def _attn_fp32(self, q, k, v): + """softmax(q k^T / 8) v with fp32 scores and softmax; q, k, v [T, H, L (logical), 64] -> [T, H, L, 64].""" + ttnn = _ttnn() + T, H, lp = self.T, self.heads, self.lp + kt = ttnn.transpose(k, -2, -1, memory_config=self.mem) # [T, H, 64, L] + outs = [] + for r0 in range(0, lp, self.q_rows): + r1 = min(lp, r0 + self.q_rows) + qc = q if (r0, r1) == (0, lp) else ttnn.slice(full_view(q), [0, 0, r0, 0], [T, H, r1, HEAD_DIM], memory_config=self.mem) + qs = ttnn.multiply(qc, HEAD_DIM ** -0.5, memory_config=self.mem) # exact (power of 2) + if qc is not q: + ttnn.deallocate(qc) + s = ttnn.matmul(qs, kt, memory_config=self.mem, dtype=ttnn.float32, compute_kernel_config=self.cfgs.mm) + ttnn.deallocate(qs) + p = ttnn.softmax(s, dim=-1, numeric_stable=True, memory_config=self.mem, compute_kernel_config=self.cfgs.mm) + ttnn.deallocate(s) + p16 = ttnn.typecast(p, ttnn.bfloat16, memory_config=self.mem) + ttnn.deallocate(p) + outs.append(ttnn.matmul(p16, v, memory_config=self.mem, dtype=ttnn.bfloat16, compute_kernel_config=self.cfgs.mm)) + ttnn.deallocate(p16) + ttnn.deallocate(kt) + if len(outs) == 1: + return outs[0] + o = ttnn.concat([full_view(t) for t in outs], dim=2, memory_config=self.mem) + for t in outs: + ttnn.deallocate(t) + return o + + # -- blocks + def block_within(self, x, bw: BlockWeights, freeze_prefix: bool = False, fp32_attn: bool = False): + """Within-frame block on ``x`` [T, 1, Lp, C]; ``freeze_prefix`` keeps rows >= N (prefix) unchanged.""" + ttnn = _ttnn() + T, lp, n = self.T, self.lp, self.n + h = self._ln(x, bw.n1_w, bw.n1_b) + qkv = self._qkv(h, bw) + ttnn.deallocate(h) + q, k, v = self._heads(qkv, n + NUM_PREFIX, lp, T, "frame") + ttnn.deallocate(qkv) + if fp32_attn: + o = self._attn_fp32(q, k, v) + else: + o = ttnn.transformer.scaled_dot_product_attention(q, k, v, is_causal=False, scale=HEAD_DIM ** -0.5, + program_config=self.sdpa_pc, compute_kernel_config=self.cfgs.sdpa, + memory_config=self.mem, cu_window_seqlens=self.wf_cu) + ttnn.deallocate(q) + ttnn.deallocate(k) + ttnn.deallocate(v) + a = ttnn.experimental.nlp_concat_heads(full_view(o), memory_config=self.mem) + ttnn.deallocate(o) + p = self._lin(a, bw.proj_w, bw.proj_b, dtype=self.branch_dtype) + ttnn.deallocate(a) + if freeze_prefix: + p2 = ttnn.multiply(p, self.patch_mask, memory_config=self.mem) + ttnn.deallocate(p) + p = p2 + x1 = ttnn.add(x, p, memory_config=self.mem, dtype=self.resid_dtype) + ttnn.deallocate(p) + h = self._ln(x1, bw.n2_w, bw.n2_b) + f = self._mlp(h, bw) + ttnn.deallocate(h) + if freeze_prefix: + f2 = ttnn.multiply(f, self.patch_mask, memory_config=self.mem) + ttnn.deallocate(f) + f = f2 + x2 = ttnn.add(x1, f, memory_config=self.mem, dtype=self.resid_dtype) + ttnn.deallocate(f) + ttnn.deallocate(x1) + return x2 + + def block_cross(self, x, bw: BlockWeights): + """Cross-frame block, T > 1 (see module doc): ONE windowed SDPA over the joint sequence + ``[pooled prefix (5) ; patches of frames 0..T-1]``; ``vf_cu`` puts the pooled prefix and frames ``< n`` in + window 0 and frames ``>= n`` in window 1, ``vf_w`` averages the prefix of frames ``< n``.""" + ttnn = _ttnn() + T, n, c, lp = self.T, self.n, self.c, self.lp + tn, sj = T * n, self.s_joint + sjp = ceil32(sj) + prefix_in = ttnn.slice(x, [0, 0, n, 0], [T, 1, n + NUM_PREFIX, c], memory_config=self.mem) # [T, 1, 5, C] + if n % 32 == 0: + xc = view(ttnn.slice(x, [0, 0, 0, 0], [T, 1, n, c], memory_config=self.mem), [1, 1, tn, c], [1, 1, tn, c]) + else: + xs = view(x, [T, 1, n, c], [T, 1, lp, c]) if lp == ceil32(n) else ttnn.slice(x, [0, 0, 0, 0], [T, 1, n, c], memory_config=self.mem) + xc = ttnn.reshape(xs, [1, 1, tn, c], memory_config=self.mem) + if lp != ceil32(n): # xs is a slice copy (else a view of x, which the caller owns) + free_unless_shared(xs, xc) + wp = ttnn.multiply(prefix_in, self.vf_w, memory_config=self.mem, dtype=self.resid_dtype) + pooled = ttnn.sum(wp, dim=0, keepdim=True, memory_config=self.mem) # [1, 1, 5, C]: mean over frames < n + ttnn.deallocate(wp) + xj = ttnn.concat([pooled, xc], dim=2, memory_config=self.mem) # [1, 1, 5 + T * N, C] + ttnn.deallocate(pooled) + ttnn.deallocate(xc) + h = self._ln(xj, bw.n1_w, bw.n1_b) + qkv = self._qkv(h, bw) + ttnn.deallocate(h) + q, k, v = self._heads(qkv, sj, sjp, 1, "clip") + ttnn.deallocate(qkv) + o = ttnn.transformer.scaled_dot_product_attention( + q, k, v, is_causal=False, scale=HEAD_DIM ** -0.5, program_config=self.win_pc, + compute_kernel_config=self.cfgs.sdpa, memory_config=self.mem, cu_window_seqlens=self.vf_cu) + for t in (q, k, v): + ttnn.deallocate(t) + a = ttnn.experimental.nlp_concat_heads(full_view(o), memory_config=self.mem) # [1, 1, sjp, C] + ttnn.deallocate(o) + p = self._lin(a, bw.proj_w, bw.proj_b, dtype=self.branch_dtype) + ttnn.deallocate(a) + x1 = ttnn.add(full_view(xj), p, memory_config=self.mem, dtype=self.resid_dtype) + ttnn.deallocate(p) + ttnn.deallocate(xj) + h = self._ln(x1, bw.n2_w, bw.n2_b) + f = self._mlp(h, bw) + ttnn.deallocate(h) + x2 = ttnn.add(x1, f, memory_config=self.mem, dtype=self.resid_dtype) + ttnn.deallocate(f) + ttnn.deallocate(x1) + # back to frames: [T, 1, N, C] ++ the unchanged block-input prefix rows + xpat = ttnn.slice(x2, [0, 0, NUM_PREFIX, 0], [1, 1, sj, c], memory_config=self.mem) # [1, 1, T * N, C] + ttnn.deallocate(x2) + xf = ttnn.reshape(xpat, [T, 1, n, c], memory_config=self.mem) + free_unless_shared(xpat, xf) # N % 32 == 0: xf is a view of xpat + out = ttnn.concat([xf, prefix_in], dim=2, memory_config=self.mem) # [T, 1, N + 5, C] + ttnn.deallocate(xf) + ttnn.deallocate(prefix_in) + return full_view(out) + + def embed(self, patches): + """``patches`` [1, 1, T * Np, 768] -> X [T, 1, Lp, C].""" + ttnn = _ttnn() + T, np_, lp, c = self.T, self.np_, self.lp, self.c + p = view(patches, [T, 1, np_, 768], [T, 1, np_, 768]) + if self.pad_rows is not None: + p = ttnn.concat([p, self.pad_rows], dim=2, memory_config=self.mem) + e = ttnn.linear(p, self.tw.pe_w, memory_config=self.mem, dtype=self.act_dtype, compute_kernel_config=self.cfgs.mm) + if self.pad_rows is not None: + ttnn.deallocate(p) + x = ttnn.add(e, self.embed_rows, memory_config=self.mem, dtype=self.resid_dtype) + ttnn.deallocate(e) + return x + + def run(self, patches) -> List[object]: + ttnn = _ttnn() + x = self.embed(patches) + taps = [] + for i in range(self.cfg.depth): + bw = self.tw.blocks[i] + if i in self.cross_blocks: + if self.cross_compact: + y = self.block_cross(x, bw) + else: + y = self.block_within(x, bw, freeze_prefix=True, fp32_attn=i in self.fp32_blocks) + else: + y = self.block_within(x, bw, fp32_attn=i in self.fp32_blocks) + if not any(x is t for t in taps): + ttnn.deallocate(x) + x = y + if self.hook is not None: + self.hook(i, x) + if i in self.tap_blocks: + taps.append(x) + if not any(x is t for t in taps): + ttnn.deallocate(x) + return taps + + +# ----------------------------------------------------------------------------------------------- ENC engine + + +class Engine: + """ttnn ENC engine for one :class:`StageShape`: ``run(patches) -> [tap0, tap1, tap2, tap3]`` (module doc). + + Runtime valid-frame count: ``supports_valid_frames = True``; ``set_valid_frames(n)`` (host, before ``run`` / a + trace replay) makes the T-frame program process frames ``[0, n)`` as an n-frame clip (module doc).""" + + supports_valid_frames = True + + def __init__(self, device, weights, shape: StageShape, size: Optional[str] = None): + if isinstance(weights, dict): + if size is None: + raise ValueError("size is required with host weights") + weights = Engine.prepare_weights(device, weights, size) + self.device = device + self.shape = shape + self.weights = weights + cfg = weights.cfg + self.trunk = Trunk(device, weights, shape, joint_cross=True, tap_blocks=cfg.reassembled_blocks, + cross_blocks=cfg.cross_frame_blocks, fp32_blocks=fp32_attn_blocks(cfg.name)) + + @staticmethod + def prepare_weights(device, host_weights, size: str) -> TrunkWeights: + return upload_trunk(device, host_weights, ref.SIZES[size], "encoder.") + + def set_valid_frames(self, n: int) -> None: + self.trunk.set_valid_frames(n) + + def input_spec(self) -> Tuple[Tuple[int, ...], str]: + return (1, 1, self.shape.frames * self.shape.np_, 768), "bf16 TILE DRAM" + + def run(self, patches) -> List[object]: + ttnn = _ttnn() + s = self.shape + T, np_, lp, c = s.frames, s.np_, s.lp, self.weights.cfg.dim + out = [] + for x in self.trunk.run(patches): + if lp != np_: + y = ttnn.slice(x, [0, 0, 0, 0], [T, 1, np_, c], memory_config=ttnn.DRAM_MEMORY_CONFIG) + ttnn.deallocate(x) + else: + y = x + if y.dtype != ttnn.bfloat16: # fp32 residual stream -> bf16 taps (stage contract) + y2 = ttnn.typecast(y, ttnn.bfloat16, memory_config=ttnn.DRAM_MEMORY_CONFIG) + ttnn.deallocate(y) + y = y2 + out.append(view(y, [1, 1, T * np_, c], [1, 1, T * np_, c])) + return out diff --git a/code/tt_depthpro2/tt/ttnn_fov.py b/code/tt_depthpro2/tt/ttnn_fov.py new file mode 100644 index 0000000000000000000000000000000000000000..1ed99896bab110fd106f8d7d0ed14be4f7d4996d --- /dev/null +++ b/code/tt_depthpro2/tt/ttnn_fov.py @@ -0,0 +1,219 @@ +# SPDX-License-Identifier: Apache-2.0 +"""FOV stage, ttnn baseline: DINOv3 ViT-S/16 trunk (taps incl. prefix) + attention head -> logits. + +Stage contract (SPEC §3): + +* ``FOV.in`` ``fpatches`` ``[1, 1, T * Nfp, 768]`` bf16 TILE DRAM, from the host-resized frames + (``reference.fov_resize``, then ``tt.weights.unfold_patches``); ``Nfp = ceil32(gh * gw)``. +* ``FOV.out`` ``logits`` ``[1, 1, T, 2]`` float32 TILE DRAM (``ttnn.to_torch(...).reshape(T, 2)``); degrees on the host + with ``reference.fov_logits_to_deg``. + +Trunk: :class:`tt.ttnn_enc.Trunk` with ``joint_cross=False`` (blocks 5/7/9/11 keep their input prefix rows, no joint +attention). Head (``reference.fov_head``), all on the device: + +* ``y = Linear(1536 -> 248)(cat_i LN_i(tap_i))`` on every token row ``[T, 1, Lp, 248]``; +* the head sequence ``[query ; prefix + prefix_embed ; avgpool2x2(patches) + sincos]`` is ONE matmul with a constant + gather / pooling matrix ``G`` (``[S_h, Lp]``: prefix-row selection and the ceil-mode 2x2 average weights 1, 1/2, 1/4, + all exact in bf16) plus a constant row tensor (query, prefix_embed, sincos code); +* 2 timm ViT blocks (dim 248, 4 heads of 62 dims zero-padded to 64 on the device, scale 1/sqrt(62)), LN, Linear(248 -> 2) + on the query row. +""" + +from __future__ import annotations + +import os +from typing import List, Optional, Tuple + +import torch + +from ..reference import model as ref +from . import NUM_PREFIX, StageShape, ceil32 +from .ttnn_enc import Configs, Trunk, _ttnn, fp32_attn_blocks, full_view, sdpa_windowed, view +from .weights import FOV_HD, FOV_HDIM_P, FOV_HEADS, FovWeights, dev_tensor, fov_head_scale, upload_fov + + +def head_gather(shape: StageShape) -> Tuple[torch.Tensor, int]: + """``G^T`` ``[Lp, S_hp]`` (float32) and ``S_h``: head row 0 = query slot (zero), rows 1..5 = prefix rows N..N+4, + rows 6.. = ceil-mode 2x2 average of the patch grid (raster order).""" + gh, gw, n, lp = shape.gh, shape.gw, shape.n, shape.lp + ph, pw = -(-gh // 2), -(-gw // 2) + s_h = 1 + NUM_PREFIX + ph * pw + g = torch.zeros(ceil32(s_h), lp) + for j in range(NUM_PREFIX): + g[1 + j, n + j] = 1.0 + for a in range(ph): + for b in range(pw): + rows = [r for r in (2 * a, 2 * a + 1) if r < gh] + cols = [c for c in (2 * b, 2 * b + 1) if c < gw] + wgt = 1.0 / (len(rows) * len(cols)) + for r in rows: + for c in cols: + g[1 + NUM_PREFIX + a * pw + b, r * gw + c] = wgt + return g.t().contiguous(), s_h + + +class Engine: + """ttnn FOV engine for one :class:`StageShape` (the fov-resized frame size): ``run(fpatches) -> logits [1, 1, T, 2]``.""" + + def __init__(self, device, weights, shape: StageShape, size: Optional[str] = None): + ttnn = _ttnn() + if isinstance(weights, dict): + weights = Engine.prepare_weights(device, weights, "fov") + self.device = device + self.w: FovWeights = weights + self.shape = shape + self.cfgs = Configs(device) + self.mem = ttnn.DRAM_MEMORY_CONFIG + cfg = ref.FOV_TRUNK + self.trunk = Trunk(device, weights.trunk, shape, joint_cross=False, tap_blocks=cfg.reassembled_blocks, + cross_blocks=cfg.cross_frame_blocks, fp32_blocks=fp32_attn_blocks("fov"), cfgs=self.cfgs) + gt, s_h = head_gather(shape) + self.s_h, self.s_hp = s_h, gt.shape[1] + self.gather_t = dev_tensor(gt.reshape(1, 1, *gt.shape), device) + ph, pw = -(-shape.gh // 2), -(-shape.gw // 2) + add = torch.zeros(1, 1, self.s_hp, FOV_HD) + add[0, 0, 0] = weights.head.query_host + add[0, 0, 1:1 + NUM_PREFIX] = weights.head.prefix_embed_host + add[0, 0, 1 + NUM_PREFIX:s_h] = ref.sincos_2d(ph, pw, FOV_HD) + self.head_add_host = add + self.head_add = dev_tensor(add, device) + self.head_pc = self.cfgs.sdpa_program(s_h, s_h) + self.head_cu = (self.trunk._dev_cu(torch.tensor([0, s_h], dtype=torch.int32)) + if sdpa_windowed(shape.frames, FOV_HEADS) else None) + # DEPTHPRO2_TTNN_FOV_HEAD = fp32 (default: the official head runs in float32 -- fp32 activations, exact + # LayerNorm over the 248 columns, fp32-score attention on fp32 q / k / v) | bf16 (bf16 activations, SDPA) + self.head32 = os.environ.get("DEPTHPRO2_TTNN_FOV_HEAD", "fp32") == "fp32" + self.act = ttnn.float32 if self.head32 else ttnn.bfloat16 + if self.head32: + cm = torch.zeros(1, 1, 1, FOV_HD) + cm[...] = 1.0 + self.colmask = dev_tensor(cm, device, dtype=ttnn.float32) # logical 248 columns, padding 0 + add = self.head_add_host + self.head_add = dev_tensor(add, device, dtype=ttnn.float32) + + @staticmethod + def prepare_weights(device, host_weights, size: str = "fov") -> FovWeights: + return upload_fov(device, host_weights) + + def _ln(self, x, w, b): + """LayerNorm over the 248 logical columns (padding columns are zero in and out).""" + ttnn = _ttnn() + if not self.head32: + return ttnn.layer_norm(x, epsilon=ref.LN_EPS, weight=w, bias=b, memory_config=self.mem, + compute_kernel_config=self.cfgs.ln) + mem, cfg = self.mem, self.cfgs.ln + s1 = ttnn.sum(x, dim=-1, keepdim=True, memory_config=mem, compute_kernel_config=cfg) + mu = ttnn.multiply(s1, 1.0 / FOV_HD, memory_config=mem) + ttnn.deallocate(s1) + d = ttnn.subtract(x, mu, memory_config=mem) + ttnn.deallocate(mu) + xc = ttnn.multiply(d, self.colmask, memory_config=mem) + ttnn.deallocate(d) + sq = ttnn.multiply(xc, xc, memory_config=mem) + s2 = ttnn.sum(sq, dim=-1, keepdim=True, memory_config=mem, compute_kernel_config=cfg) + ttnn.deallocate(sq) + var = ttnn.multiply(s2, 1.0 / FOV_HD, memory_config=mem) + ttnn.deallocate(s2) + ve = ttnn.add(var, ref.LN_EPS, memory_config=mem) + ttnn.deallocate(var) + rs = ttnn.rsqrt(ve, memory_config=mem) + ttnn.deallocate(ve) + xn = ttnn.multiply(xc, rs, memory_config=mem) + ttnn.deallocate(xc) + ttnn.deallocate(rs) + y = ttnn.multiply(xn, w, memory_config=mem) + ttnn.deallocate(xn) + out = ttnn.add(y, b, memory_config=mem) + ttnn.deallocate(y) + return out + + def _lin(self, x, w, b=None, act=None, dtype=None): + ttnn = _ttnn() + return ttnn.linear(x, w, bias=b, activation=act, memory_config=self.mem, dtype=dtype or self.act, + compute_kernel_config=self.cfgs.mm) + + def _attn32(self, q, k, v): + """fp32-score attention on fp32 q / k / v [T, 4, S_h (logical), 64] (scale 1/sqrt(62)).""" + ttnn = _ttnn() + mem = self.mem + qs = ttnn.multiply(q, fov_head_scale(), memory_config=mem) + kt = ttnn.transpose(k, -2, -1, memory_config=mem) + sc = ttnn.matmul(qs, kt, memory_config=mem, dtype=ttnn.float32, compute_kernel_config=self.cfgs.mm) + ttnn.deallocate(qs) + ttnn.deallocate(kt) + pr = ttnn.softmax(sc, dim=-1, numeric_stable=True, memory_config=mem, compute_kernel_config=self.cfgs.mm) + ttnn.deallocate(sc) + o = ttnn.matmul(pr, v, memory_config=mem, dtype=ttnn.float32, compute_kernel_config=self.cfgs.mm) + ttnn.deallocate(pr) + return o + + def _head_block(self, x, p): + ttnn = _ttnn() + T, s_h, s_hp = self.shape.frames, self.s_h, self.s_hp + h = self._ln(x, p["n1_w"], p["n1_b"]) + qkv = self._lin(h, p["qkv_w"], p["qkv_b"]) + ttnn.deallocate(h) + q, k, v = ttnn.experimental.nlp_create_qkv_heads(qkv, num_heads=FOV_HEADS, num_kv_heads=FOV_HEADS, + transpose_k_heads=False, memory_config=self.mem) + ttnn.deallocate(qkv) + shp, pad = [T, FOV_HEADS, s_h, FOV_HDIM_P], [T, FOV_HEADS, s_hp, FOV_HDIM_P] + if self.head32: + o = self._attn32(view(q, shp, pad), view(k, shp, pad), view(v, shp, pad)) + else: + o = ttnn.transformer.scaled_dot_product_attention(view(q, shp, pad), view(k, shp, pad), view(v, shp, pad), + is_causal=False, scale=fov_head_scale(), program_config=self.head_pc, + compute_kernel_config=self.cfgs.sdpa, memory_config=self.mem, + cu_window_seqlens=self.head_cu) + for t in (q, k, v): + ttnn.deallocate(t) + a = ttnn.experimental.nlp_concat_heads(full_view(o), memory_config=self.mem) + ttnn.deallocate(o) + pr = self._lin(a, p["proj_w"], p["proj_b"]) + ttnn.deallocate(a) + x1 = ttnn.add(x, pr, memory_config=self.mem) + ttnn.deallocate(pr) + h = self._ln(x1, p["n2_w"], p["n2_b"]) + m = self._lin(h, p["fc1_w"], p["fc1_b"], act="gelu") + ttnn.deallocate(h) + f = self._lin(m, p["fc2_w"], p["fc2_b"]) + ttnn.deallocate(m) + x2 = ttnn.add(x1, f, memory_config=self.mem) + ttnn.deallocate(f) + ttnn.deallocate(x1) + return x2 + + def run(self, fpatches) -> object: + ttnn = _ttnn() + T = self.shape.frames + hw = self.w.head + taps = self.trunk.run(fpatches) # 4 x [T, 1, Lp, 384], incl. prefix rows + normed = [self.trunk._ln(t, hw.tap_n_w[i], hw.tap_n_b[i]) for i, t in enumerate(taps)] # 384-wide: exact LN + for t in taps: + ttnn.deallocate(t) + cat = ttnn.concat(normed, dim=-1, memory_config=self.mem) # [T, 1, Lp, 1536] + for t in normed: + ttnn.deallocate(t) + y = self._lin(cat, hw.proj_w, hw.proj_b) # [T, 1, Lp, 248] + ttnn.deallocate(cat) + yt = ttnn.transpose(y, -2, -1, memory_config=self.mem) # [T, 1, 248, Lp] + ttnn.deallocate(y) + zt = ttnn.matmul(yt, self.gather_t, memory_config=self.mem, dtype=self.act, compute_kernel_config=self.cfgs.mm) + ttnn.deallocate(yt) + z = ttnn.transpose(zt, -2, -1, memory_config=self.mem) # [T, 1, S_hp, 248] + ttnn.deallocate(zt) + x = ttnn.add(z, self.head_add, memory_config=self.mem) + ttnn.deallocate(z) + for p in hw.blocks: + x2 = self._head_block(x, p) + ttnn.deallocate(x) + x = x2 + q0 = ttnn.slice(full_view(x), [0, 0, 0, 0], [T, 1, 32, FOV_HD], memory_config=self.mem) + ttnn.deallocate(x) + h = self._ln(q0, hw.norm_w, hw.norm_b) + ttnn.deallocate(q0) + lg = ttnn.linear(h, hw.out_w, bias=hw.out_b, memory_config=self.mem, dtype=ttnn.float32, + compute_kernel_config=self.cfgs.mm) # [T, 1, 32, 2] float32 + ttnn.deallocate(h) + r0 = ttnn.slice(lg, [0, 0, 0, 0], [T, 1, 1, 2], memory_config=self.mem) + ttnn.deallocate(lg) + return ttnn.reshape(r0, [1, 1, T, 2], memory_config=self.mem) diff --git a/code/tt_depthpro2/tt/ttnn_kv.py b/code/tt_depthpro2/tt/ttnn_kv.py new file mode 100644 index 0000000000000000000000000000000000000000..2885c060258a8dc1f97a749e3883bdc3c44edeb4 --- /dev/null +++ b/code/tt_depthpro2/tt/ttnn_kv.py @@ -0,0 +1,217 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Unbuffered video on the device: one-frame ENC step attending a key-value cache of the last frames (ttnn). + +Semantics = ``cpu_engine.CPUEngine.inverse_depth_step`` / ``CPUKVCache`` (SPEC §1 "Unbuffered"): within-frame blocks +as usual; each cross-frame block takes this frame's patch queries over [pooled prefix ; the patch keys / values of +the last ``fill = min(frames seen + 1, window)`` frames, this one included] and keeps the frame's own prefix rows; +the pooled prefix is the mean of the block-input prefix of those ``fill`` frames. + +Device design (compiled once per bucket for a ring of ``W = max_frames`` frames; any cache window ``<= W``): + +* per cache (:class:`KVState`) and cross-frame block: ``k_old`` / ``v_old`` ``[1, H, (W - 1) * N, 64]`` bf16 TILE + (the patch K / V of the ``W - 1`` previous frames, newest first, compact rows), ``p_old`` ``[W - 1, 1, 5, C]`` + float32 TILE (their block-input prefix rows); +* step, per cross-frame block: ``kseq = [pk (5) ; k_new (N) ; k_old]`` (one ``ttnn.concat``), ONE windowed SDPA + (``cu_window_seqlens`` = ``step_cu`` = ``[0, 5 + fill * N, 5 + W * N]``: window 0 = the live keys), pooled prefix + = ``sum(step_w * [prefix_new ; p_old])`` (``step_w`` = ``1 / fill`` on the first ``fill`` slots); then the ring + shifts in place: ``k_old <- kseq[5 : 5 + (W - 1) * N]``, ``p_old <- [prefix_new ; p_old][: W - 1]`` + (``ttnn.copy`` into the persistent state, inside the trace); +* ``step_cu`` / ``step_w`` are per-bucket persistent inputs the host writes before each replay: one trace per + cache serves every fill state (no re-capture). +""" + +from __future__ import annotations + +from typing import List, Optional + +import torch + +from . import NUM_PREFIX, StageShape, ceil32 +from .ttnn_enc import HEAD_DIM, Configs, Trunk, _ttnn, fp32_attn_blocks, free_unless_shared, full_view, view +from .weights import BlockWeights, TrunkWeights, dev_tensor + + +def step_cu(window_ring: int, fill: int, n_patches: int) -> torch.Tensor: + """``step_cu`` (int32, 3 values): window 0 = ``[pooled prefix ; the fill newest frames]`` of + ``kseq = [pk (5) ; k_new (N) ; k_old ((W - 1) * N)]``.""" + return torch.tensor([0, NUM_PREFIX + fill * n_patches, NUM_PREFIX + window_ring * n_patches], dtype=torch.int32) + + +def step_weights(window_ring: int, fill: int) -> torch.Tensor: + w = torch.zeros(window_ring, 1, 1, 1) + w[:fill] = 1.0 / fill + return w + + +class KVState: + """Device ring state of ONE cache (one stream) for one bucket: per cross-frame block ``k_old``, ``v_old``, + ``p_old`` (module doc). Allocated before any trace capture (``DepthPro2Device`` keeps a pool).""" + + def __init__(self, device, shape: StageShape, cfg, window_ring: int, cross_blocks): + ttnn = _ttnn() + self.window_ring = window_ring + self.blocks = {} + rows = (window_ring - 1) * shape.n + self.nbytes = 0 + if window_ring > 1: + for i in cross_blocks: + kv = [] + for _ in range(2): + t = ttnn.reshape(dev_tensor(torch.zeros(1, cfg.heads, ceil32(rows), HEAD_DIM), device), + ttnn.Shape([1, cfg.heads, rows, HEAD_DIM]), + ttnn.Shape([1, cfg.heads, ceil32(rows), HEAD_DIM])) + kv.append(t) + p = view(dev_tensor(torch.zeros(window_ring - 1, 1, 32, cfg.dim), device, dtype=ttnn.float32), + [window_ring - 1, 1, NUM_PREFIX, cfg.dim], [window_ring - 1, 1, 32, cfg.dim]) + self.blocks[i] = (kv[0], kv[1], p) + self.nbytes += 2 * cfg.heads * ceil32(rows) * HEAD_DIM * 2 + (window_ring - 1) * 32 * cfg.dim * 4 + + def free(self) -> None: + ttnn = _ttnn() + for k, v, p in self.blocks.values(): + for t in (k, v, p): + ttnn.deallocate(t) + self.blocks = {} + + +class StepEncoder: + """ttnn ENC in step mode for one bucket (``shape.frames == 1``): ``run(patches, state) -> 4 taps`` + (``[1, 1, Np, C]`` bf16, the ENC.out contract with T = 1).""" + + def __init__(self, device, weights: TrunkWeights, shape: StageShape, window_ring: int): + ttnn = _ttnn() + if shape.frames != 1: + raise ValueError("StepEncoder works on one frame") + self.device = device + self.w = weights + self.cfg = weights.cfg + self.shape = shape + self.window_ring = int(window_ring) + self.cfgs = Configs(device) + self.trunk = Trunk(device, weights, shape, joint_cross=False, tap_blocks=self.cfg.reassembled_blocks, + cross_blocks=self.cfg.cross_frame_blocks, fp32_blocks=fp32_attn_blocks(self.cfg.name), + cfgs=self.cfgs) + n = shape.n + self.np_ = ceil32(n) + # RoPE table of the patch rows alone ([N] rows padded to Np) + from .ttnn_enc import rope_rows + + cos, sin = rope_rows(shape.gh, shape.gw, self.np_) + self.trunk.add_rope_table("patch", cos, sin) + self.s_keys = NUM_PREFIX + self.window_ring * n + self.pc = self.cfgs.sdpa_program(n, self.s_keys) + self.cu = self.trunk._dev_cu(step_cu(self.window_ring, 1, n)) + self.wts = dev_tensor(step_weights(self.window_ring, 1), device, dtype=ttnn.float32) + + def set_fill(self, fill: int) -> None: + """Host call before a replay: ``fill`` live frames (this one included).""" + ttnn = _ttnn() + if not 1 <= fill <= self.window_ring: + raise ValueError(f"fill {fill} outside 1..{self.window_ring}") + ttnn.copy_host_to_device_tensor(ttnn.from_torch(step_cu(self.window_ring, fill, self.shape.n), dtype=ttnn.int32, + layout=ttnn.ROW_MAJOR_LAYOUT), self.cu, cq_id=0) + ttnn.copy_host_to_device_tensor(ttnn.from_torch(step_weights(self.window_ring, fill), dtype=ttnn.float32, + layout=ttnn.TILE_LAYOUT), self.wts, cq_id=0) + + def block_step(self, x, bw: BlockWeights, st): + """Cross-frame block in step mode on ``x`` [1, 1, Lp, C] (module doc).""" + ttnn = _ttnn() + tr = self.trunk + n, c, lp, W = self.shape.n, self.cfg.dim, self.shape.lp, self.window_ring + np_, H = self.np_, self.cfg.heads + mem = tr.mem + prefix_in = ttnn.slice(x, [0, 0, n, 0], [1, 1, n + NUM_PREFIX, c], memory_config=mem) # [1, 1, 5, C] + p_all = ttnn.concat([prefix_in, st[2]], dim=0, memory_config=mem) if W > 1 else prefix_in # [W, 1, 5, C] + wp = ttnn.multiply(p_all, self.wts, memory_config=mem, dtype=tr.resid_dtype) + pooled = ttnn.sum(wp, dim=0, keepdim=True, memory_config=mem) # [1, 1, 5, C] + ttnn.deallocate(wp) + if lp == np_: + xp = view(x, [1, 1, n, c], [1, 1, lp, c]) + else: + xp = ttnn.slice(x, [0, 0, 0, 0], [1, 1, n, c], memory_config=mem) + h = tr._ln(xp, bw.n1_w, bw.n1_b) + qkv = tr._qkv(h, bw) + ttnn.deallocate(h) + q, k, v = tr._heads(qkv, n, np_, 1, "patch") + ttnn.deallocate(qkv) + hp = tr._ln(pooled, bw.n1_w, bw.n1_b) + ttnn.deallocate(pooled) + qkvp = tr._qkv(hp, bw) + ttnn.deallocate(hp) + qp, kp, vp = tr._heads(qkvp, NUM_PREFIX, 32, 1) + ttnn.deallocate(qkvp) + ttnn.deallocate(qp) + if W > 1: + kseq = ttnn.concat([kp, k, st[0]], dim=2, memory_config=mem) # [1, H, 5 + W * N, 64] + vseq = ttnn.concat([vp, v, st[1]], dim=2, memory_config=mem) + else: + kseq = ttnn.concat([kp, k], dim=2, memory_config=mem) + vseq = ttnn.concat([vp, v], dim=2, memory_config=mem) + for t in (k, v, kp, vp): + ttnn.deallocate(t) + o = ttnn.transformer.scaled_dot_product_attention( + q, kseq, vseq, is_causal=False, scale=HEAD_DIM ** -0.5, program_config=self.pc, + compute_kernel_config=self.cfgs.sdpa, memory_config=mem, cu_window_seqlens=self.cu) + ttnn.deallocate(q) + if W > 1: # ring shift: the W - 1 newest frames (this one first) become the old slots + rows = (W - 1) * n + for seq, dst in ((kseq, st[0]), (vseq, st[1])): + nxt = ttnn.slice(seq, [0, 0, NUM_PREFIX, 0], [1, H, NUM_PREFIX + rows, HEAD_DIM], memory_config=mem) + ttnn.copy(nxt, dst) + ttnn.deallocate(nxt) + pn = ttnn.slice(p_all, [0, 0, 0, 0], [W - 1, 1, NUM_PREFIX, c], memory_config=mem) + ttnn.copy(pn, st[2]) + ttnn.deallocate(pn) + ttnn.deallocate(p_all) + ttnn.deallocate(kseq) + ttnn.deallocate(vseq) + a = ttnn.experimental.nlp_concat_heads(full_view(o), memory_config=mem) # [1, 1, Np, C] + ttnn.deallocate(o) + p = tr._lin(a, bw.proj_w, bw.proj_b, dtype=tr.branch_dtype) + ttnn.deallocate(a) + x1 = ttnn.add(full_view(xp), p, memory_config=mem, dtype=tr.resid_dtype) + ttnn.deallocate(p) + if lp != np_: + ttnn.deallocate(xp) + h = tr._ln(x1, bw.n2_w, bw.n2_b) + f = tr._mlp(h, bw) + ttnn.deallocate(h) + x2 = ttnn.add(x1, f, memory_config=mem, dtype=tr.resid_dtype) + ttnn.deallocate(f) + ttnn.deallocate(x1) + out = ttnn.concat([view(x2, [1, 1, n, c], [1, 1, np_, c]), prefix_in], dim=2, memory_config=mem) # [1, 1, N + 5, C] + ttnn.deallocate(x2) + ttnn.deallocate(prefix_in) + return full_view(out) + + def run(self, patches, state: KVState) -> List[object]: + ttnn = _ttnn() + tr = self.trunk + s = self.shape + np_, lp, c = s.np_, s.lp, self.cfg.dim + x = tr.embed(patches) + taps = [] + for i in range(self.cfg.depth): + bw = self.w.blocks[i] + if i in self.cfg.cross_frame_blocks: + y = self.block_step(x, bw, state.blocks.get(i)) + else: + y = tr.block_within(x, bw, fp32_attn=i in tr.fp32_blocks) + if not any(x is t for t in taps): + ttnn.deallocate(x) + x = y + if i in self.cfg.reassembled_blocks: + taps.append(x) + if not any(x is t for t in taps): + ttnn.deallocate(x) + out = [] + for x in taps: + y = ttnn.slice(x, [0, 0, 0, 0], [1, 1, np_, c], memory_config=tr.mem) if lp != np_ else x + if y is not x: + ttnn.deallocate(x) + if y.dtype != ttnn.bfloat16: + y2 = ttnn.typecast(y, ttnn.bfloat16, memory_config=tr.mem) + ttnn.deallocate(y) + y = y2 + out.append(view(y, [1, 1, np_, c], [1, 1, np_, c])) + return out diff --git a/code/tt_depthpro2/tt/weights.py b/code/tt_depthpro2/tt/weights.py new file mode 100644 index 0000000000000000000000000000000000000000..a7f2f5cf647d5ac49594bbee4cb2d8cd7dfec5ca --- /dev/null +++ b/code/tt_depthpro2/tt/weights.py @@ -0,0 +1,330 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Safetensors -> device tensors, per stage (ttnn baseline engines). + +Host preparation happens in float32 and every device tensor is rounded to its device dtype exactly once: + +* linear weights are stored transposed (``[in, out]``, what ``ttnn.linear`` wants); +* LayerScale is folded into the projection it scales: ``gamma * (a @ W^T + b) = a @ (W^T * gamma) + b * gamma``; +* 16x16 patch embedding = matmul with ``W.reshape(C, 768).T``; the host unfolds patches in ``(c, ky, kx)`` order + (:func:`unfold_patches`); +* decoder convolutions stay ``[O, I, kh, kw]`` host tensors (``ttnn.conv2d`` prepares them on its first call); + 1x1 convolutions become matmul weights. + +``load_weights(dir)`` reads ``model.safetensors`` into a name -> float32 torch dict (same as the reference loader). +""" + +from __future__ import annotations + +import math +import os +from dataclasses import dataclass, field +from typing import Dict, List, Optional + +import torch + +from ..reference import model as ref +from . import PATCH + +HostDict = Dict[str, torch.Tensor] + + +def load_weights(model_dir: str) -> HostDict: + """``/model.safetensors`` -> name -> float32 tensor.""" + return ref.load_safetensors(os.path.join(model_dir, "model.safetensors")) + + +def unfold_patches(x: torch.Tensor, np_rows: Optional[int] = None) -> torch.Tensor: + """Padded frames ``[T, 3, Hp, Wp]`` -> patches ``[T * Np, 768]`` (float32), rows ``(gy, gx)`` raster order, columns + ``(c, ky, kx)`` (= ``patch_embed.proj.weight.reshape(C, 768)`` order); rows ``>= N`` of each frame are zero.""" + t, c, h, w = x.shape + gh, gw = h // PATCH, w // PATCH + n = gh * gw + np_rows = np_rows or (n + 31) // 32 * 32 + p = x.reshape(t, c, gh, PATCH, gw, PATCH).permute(0, 2, 4, 1, 3, 5).reshape(t, n, c * PATCH * PATCH) + if np_rows > n: + p = torch.cat([p, p.new_zeros(t, np_rows - n, p.shape[-1])], dim=1) + return p.reshape(t * np_rows, c * PATCH * PATCH) + + +# ----------------------------------------------------------------------------------------------- device helpers + + +def _ttnn(): + import ttnn + + return ttnn + + +def dev_tensor(t: torch.Tensor, device, dtype=None, layout=None, mem=None): + ttnn = _ttnn() + return ttnn.from_torch(t.contiguous(), dtype=dtype or ttnn.bfloat16, layout=layout or ttnn.TILE_LAYOUT, device=device, + memory_config=mem or ttnn.DRAM_MEMORY_CONFIG) + + +def _wdtype(name: str): + """Weight dtype for matmul weights (``DEPTHPRO2_TTNN_WDTYPE`` = bf16 | bfp8; A/B knob, default bf16).""" + ttnn = _ttnn() + return ttnn.bfloat8_b if os.environ.get("DEPTHPRO2_TTNN_WDTYPE", "bf16") == "bfp8" else ttnn.bfloat16 + + +# ----------------------------------------------------------------------------------------------- ViT trunk + + +@dataclass +class BlockWeights: + n1_w: object + n1_b: object + qkv_w: object + qkv_b: Optional[object] + proj_w: object + proj_b: object + n2_w: object + n2_b: object + fc1_w: object = None # GELU MLP + fc1_b: object = None + fcg_w: object = None # SwiGLU gate (SiLU) branch + fcg_b: object = None + fcx_w: object = None # SwiGLU linear branch + fcx_b: object = None + fc2_w: object = None + fc2_b: object = None + + +@dataclass +class TrunkWeights: + """A DINOv3 trunk (encoder of S/B/L/H+, or the FOV trunk) on the device.""" + + cfg: ref.SizeConfig + pe_w: object # [768, C] + pe_b_host: torch.Tensor # [C] float32 (added through the per-shape row-constant) + prefix_host: torch.Tensor # [5, C] float32: cls, reg0..3 + blocks: List[BlockWeights] = field(default_factory=list) + + +def trunk_host_block(w: HostDict, p: str, swiglu: bool) -> Dict[str, Optional[torch.Tensor]]: + """Float32 host tensors of one block in matmul layout, LayerScale folded.""" + g1, g2 = w[p + ".gamma_1"], w[p + ".gamma_2"] + out = { + "n1_w": w[p + ".norm1.weight"], "n1_b": w[p + ".norm1.bias"], + "qkv_w": w[p + ".attn.qkv.weight"].t(), "qkv_b": w.get(p + ".attn.qkv.bias"), + "proj_w": w[p + ".attn.proj.weight"].t() * g1[None, :], "proj_b": w[p + ".attn.proj.bias"] * g1, + "n2_w": w[p + ".norm2.weight"], "n2_b": w[p + ".norm2.bias"], + "fc2_w": w[p + ".mlp.fc2.weight"].t() * g2[None, :], "fc2_b": w[p + ".mlp.fc2.bias"] * g2, + } + if swiglu: + out.update(fcg_w=w[p + ".mlp.fc1_g.weight"].t(), fcg_b=w[p + ".mlp.fc1_g.bias"], + fcx_w=w[p + ".mlp.fc1_x.weight"].t(), fcx_b=w[p + ".mlp.fc1_x.bias"]) + else: + out.update(fc1_w=w[p + ".mlp.fc1.weight"].t(), fc1_b=w[p + ".mlp.fc1.bias"]) + return out + + +def upload_trunk(device, w: HostDict, cfg: ref.SizeConfig, pfx: str) -> TrunkWeights: + """``pfx``: ``"encoder."`` (depth model) or ``"trunk."`` (FOV).""" + ttnn = _ttnn() + c = cfg.dim + pe = w[pfx + "patch_embed.proj.weight"].reshape(c, -1).t() + tw = TrunkWeights( + cfg=cfg, + pe_w=dev_tensor(pe, device, dtype=ttnn.bfloat16), + pe_b_host=w[pfx + "patch_embed.proj.bias"].clone(), + prefix_host=torch.cat([w[pfx + "cls_token"].reshape(1, c), w[pfx + "reg_token"].reshape(-1, c)], 0).clone(), + ) + row = lambda v: dev_tensor(v.reshape(1, -1), device) # noqa: E731 + row32 = lambda v: dev_tensor(v.reshape(1, -1), device, dtype=ttnn.float32) # noqa: E731 (LayerNorm affine) + for i in range(cfg.depth): + h = trunk_host_block(w, f"{pfx}blocks.{i}", cfg.swiglu) + wd = lambda k: None if h.get(k) is None else dev_tensor(h[k], device, dtype=_wdtype(k)) # noqa: E731 + rb = lambda k: None if h.get(k) is None else row(h[k]) # noqa: E731 + tw.blocks.append(BlockWeights( + n1_w=row32(h["n1_w"]), n1_b=row32(h["n1_b"]), qkv_w=wd("qkv_w"), qkv_b=rb("qkv_b"), proj_w=wd("proj_w"), + proj_b=rb("proj_b"), n2_w=row32(h["n2_w"]), n2_b=row32(h["n2_b"]), fc1_w=wd("fc1_w"), fc1_b=rb("fc1_b"), fcg_w=wd("fcg_w"), fcg_b=rb("fcg_b"), + fcx_w=wd("fcx_w"), fcx_b=rb("fcx_b"), fc2_w=wd("fc2_w"), fc2_b=rb("fc2_b"))) + return tw + + +# ----------------------------------------------------------------------------------------------- DPT decoder + + +@dataclass +class ConvSpec: + """A conv / conv-transpose for ``ttnn.conv2d`` / ``ttnn.conv_transpose2d`` (host weights; prepared per shape).""" + + w_host: object # ttnn host tensor [O, I, k, k] (conv) or [I, O, k, k] (conv-transpose), bf16 + b_host: Optional[object] # ttnn host tensor [1, 1, 1, O] + cin: int + cout: int + k: int + stride: int + pad: int + transpose: bool = False + + +@dataclass +class MatSpec: + """A 1x1 conv (or kernel == stride conv-transpose) as ``x @ w + b`` on NHWC rows.""" + + w: object # device [Cin, Cout'] TILE + b: Optional[object] # device [1, Cout'] TILE + cin: int + cout: int + + +@dataclass +class DecWeights: + cfg: ref.SizeConfig + reassemble_mm: List[MatSpec] # reassemble.i.0 (1x1) + reassemble_up: Dict[int, object] # i -> ConvSpec / MatSpec (i = 0: k4s4, 1: k2s2, 3: conv3x3 s2) + convs: List[ConvSpec] # decoder.convs.i (3x3, no bias) + res: Dict[str, ConvSpec] # "f{i}.r{1|2}.c{1|3}" + deconv: List[ConvSpec] # decoder.fusions.i.deconv (k2s2, no bias) + out_conv: List[MatSpec] # decoder.fusions.i.out_conv (1x1) + head0: ConvSpec + head1: ConvSpec + head2: ConvSpec + head4_w: torch.Tensor # [32] float32 + head4_b: float + host: Dict[str, torch.Tensor] = field(default_factory=dict) + + +def _host_tt(t: torch.Tensor): + ttnn = _ttnn() + return ttnn.from_torch(t.to(torch.bfloat16).contiguous(), dtype=ttnn.bfloat16) + + +def conv_spec(w: HostDict, name: str, stride: int = 1, pad: int = 0, bias: bool = True, transpose: bool = False) -> ConvSpec: + wt = w[name + ".weight"] + b = w.get(name + ".bias") if bias else None + if transpose: + cin, cout, k = wt.shape[0], wt.shape[1], wt.shape[2] + else: + cout, cin, k = wt.shape[0], wt.shape[1], wt.shape[2] + return ConvSpec(w_host=_host_tt(wt), b_host=None if b is None else _host_tt(b.reshape(1, 1, 1, -1)), cin=cin, cout=cout, + k=k, stride=stride, pad=pad, transpose=transpose) + + +def mat_spec_1x1(device, w: HostDict, name: str) -> MatSpec: + wt = w[name + ".weight"] # [O, I, 1, 1] + cout, cin = wt.shape[0], wt.shape[1] + b = w.get(name + ".bias") + return MatSpec(w=dev_tensor(wt.reshape(cout, cin).t(), device), + b=None if b is None else dev_tensor(b.reshape(1, -1), device), cin=cin, cout=cout) + + +def mat_spec_convt(device, w: HostDict, name: str) -> MatSpec: + """ConvTranspose2d with kernel == stride as one matmul: ``[*, Cin] @ [Cin, (a, b, co)]`` + depth-to-space.""" + wt = w[name + ".weight"] # [I, O, k, k] + cin, cout, k = wt.shape[0], wt.shape[1], wt.shape[2] + m = wt.permute(0, 2, 3, 1).reshape(cin, k * k * cout) + b = w.get(name + ".bias") + return MatSpec(w=dev_tensor(m, device), + b=None if b is None else dev_tensor(b.repeat(k * k).reshape(1, -1), device), cin=cin, cout=cout) + + +def upload_dec(device, w: HostDict, cfg: ref.SizeConfig, convt4_matmul: bool = True) -> DecWeights: + rm = [mat_spec_1x1(device, w, f"encoder.reassemble.{i}.0") for i in range(4)] + up = { + 0: mat_spec_convt(device, w, "encoder.reassemble.0.1") if convt4_matmul else conv_spec(w, "encoder.reassemble.0.1", 4, 0, True, True), + 1: conv_spec(w, "encoder.reassemble.1.1", 2, 0, True, True), + 3: conv_spec(w, "encoder.reassemble.3.1", 2, 1), + } + convs = [conv_spec(w, f"decoder.convs.{i}", 1, 1, bias=False) for i in range(4)] + res = {} + for i in range(4): + for r in (1, 2): + if i == 3 and r == 1: + continue + for c in (1, 3): + res[f"f{i}.r{r}.c{c}"] = conv_spec(w, f"decoder.fusions.{i}.resnet{r}.residual.{c}", 1, 1) + deconv = [conv_spec(w, f"decoder.fusions.{i}.deconv", 2, 0, bias=False, transpose=True) for i in range(4)] + out_conv = [mat_spec_1x1(device, w, f"decoder.fusions.{i}.out_conv") for i in range(4)] + return DecWeights( + cfg=cfg, reassemble_mm=rm, reassemble_up=up, convs=convs, res=res, deconv=deconv, out_conv=out_conv, + head0=conv_spec(w, "head.0", 1, 1), head1=conv_spec(w, "head.1", 2, 0, True, True), head2=conv_spec(w, "head.2", 1, 1), + head4_w=w["head.4.weight"].reshape(-1).clone(), head4_b=float(w["head.4.bias"].reshape(-1)[0]), + ) + + +# ----------------------------------------------------------------------------------------------- FOV head + +FOV_HD = ref.FOV_HEAD_DIM # 248 +FOV_HEADS = ref.FOV_HEAD_HEADS # 4 +FOV_HDIM = FOV_HD // FOV_HEADS # 62 +FOV_HDIM_P = 64 # per-head width on the device (zero-padded) +FOV_MLP = 4 * FOV_HD # 992 + + +@dataclass +class FovHeadWeights: + tap_n_w: List[object] + tap_n_b: List[object] + proj_w: object # [1536, 248] + proj_b: object # [1, 248] + blocks: List[Dict[str, object]] + norm_w: object + norm_b: object + out_w: object # [248, 2] + out_b: object # [1, 2] + query_host: torch.Tensor # [248] + prefix_embed_host: torch.Tensor # [5, 248] + + +def _head_qkv_padded(wq: torch.Tensor, bq: torch.Tensor): + """timm qkv [744, 248] (+ bias) -> [248, 3 * 4 * 64] / [768]: each head's 62 dims padded to 64 with zeros.""" + w_t = wq.t() # [248, 744], columns (s, h, d) + w_p = torch.zeros(FOV_HD, 3, FOV_HEADS, FOV_HDIM_P) + b_p = torch.zeros(3, FOV_HEADS, FOV_HDIM_P) + w_p[..., :FOV_HDIM] = w_t.reshape(FOV_HD, 3, FOV_HEADS, FOV_HDIM) + b_p[..., :FOV_HDIM] = bq.reshape(3, FOV_HEADS, FOV_HDIM) + return w_p.reshape(FOV_HD, -1), b_p.reshape(-1) + + +def _head_proj_padded(wp: torch.Tensor): + """proj [248, 248] -> [4 * 64, 248]: rows at the per-head padding dims are zero.""" + w_t = wp.t().reshape(FOV_HEADS, FOV_HDIM, FOV_HD) + w_p = torch.zeros(FOV_HEADS, FOV_HDIM_P, FOV_HD) + w_p[:, :FOV_HDIM] = w_t + return w_p.reshape(FOV_HEADS * FOV_HDIM_P, FOV_HD) + + +def upload_fov_head(device, w: HostDict) -> FovHeadWeights: + """bf16 head weights, or float32 ones with ``DEPTHPRO2_TTNN_FOV_HEAD=fp32`` (default; the official head is fp32).""" + ttnn = _ttnn() + hd = ttnn.float32 if os.environ.get("DEPTHPRO2_TTNN_FOV_HEAD", "fp32") == "fp32" else ttnn.bfloat16 + row = lambda v: dev_tensor(v.reshape(1, -1), device, dtype=hd) # noqa: E731 + hdev = lambda t: dev_tensor(t, device, dtype=hd) # noqa: E731 + + blocks = [] + for i in range(2): + p = f"head.blocks.{i}" + qkv_w, qkv_b = _head_qkv_padded(w[p + ".attn.qkv.weight"], w[p + ".attn.qkv.bias"]) + blocks.append({ + "n1_w": row(w[p + ".norm1.weight"]), "n1_b": row(w[p + ".norm1.bias"]), + "qkv_w": hdev(qkv_w), "qkv_b": row(qkv_b), + "proj_w": hdev(_head_proj_padded(w[p + ".attn.proj.weight"])), "proj_b": row(w[p + ".attn.proj.bias"]), + "n2_w": row(w[p + ".norm2.weight"]), "n2_b": row(w[p + ".norm2.bias"]), + "fc1_w": hdev(w[p + ".mlp.fc1.weight"].t()), "fc1_b": row(w[p + ".mlp.fc1.bias"]), + "fc2_w": hdev(w[p + ".mlp.fc2.weight"].t()), "fc2_b": row(w[p + ".mlp.fc2.bias"]), + }) + return FovHeadWeights( + tap_n_w=[dev_tensor(w[f"head.tap_norms.{i}.weight"].reshape(1, -1), device, dtype=_ttnn().float32) for i in range(4)], + tap_n_b=[dev_tensor(w[f"head.tap_norms.{i}.bias"].reshape(1, -1), device, dtype=_ttnn().float32) for i in range(4)], + proj_w=hdev(w["head.proj.weight"].t()), proj_b=row(w["head.proj.bias"]), + blocks=blocks, norm_w=row(w["head.norm.weight"]), norm_b=row(w["head.norm.bias"]), + out_w=hdev(w["head.out.weight"].t()), out_b=row(w["head.out.bias"]), + query_host=w["head.query"].reshape(-1).clone(), prefix_embed_host=w["head.prefix_embed"].reshape(5, -1).clone(), + ) + + +@dataclass +class FovWeights: + trunk: TrunkWeights + head: FovHeadWeights + + +def upload_fov(device, w: HostDict) -> FovWeights: + return FovWeights(trunk=upload_trunk(device, w, ref.FOV_TRUNK, "trunk."), head=upload_fov_head(device, w)) + + +def fov_head_scale() -> float: + return 1.0 / math.sqrt(FOV_HDIM) diff --git a/code/tt_depthpro2/ttaw/API.md b/code/tt_depthpro2/ttaw/API.md new file mode 100644 index 0000000000000000000000000000000000000000..3b4b1895eb515b97b79b720db1b1b01a587ef5ae --- /dev/null +++ b/code/tt_depthpro2/ttaw/API.md @@ -0,0 +1,1396 @@ +# ttaw API guide (v0.23.0) + +`ttaw` is the shared code of the 13 Autoware ports to one Blackhole p150b (PLAN.md section 1). Source of truth: +`common/ttaw/`. Every bundle gets a vendored copy at `bundles/-p150/code//ttaw/` and imports it +relatively (`from .ttaw.trace import TraceRunner`). Tests: `common/tests/host` (CPU, fake ttnn) and +`common/tests/device` (p150, through `bin/devrun`). Changes: `common/CHANGELOG.md`. + +Rules that keep one tree valid top-level and vendored: + +- relative imports only; importing any module never imports ttnn / torch / onnx, opens no device, reads no + environment and touches no network (host tests and the image's `verify:` step import everything without a device); +- every optimization knob is read once at model build and has an env A/B switch (`ttaw.knobs`); +- kernel `.cpp` files are package data under `ops/kernels/`, located with `ops.kernel_path(name)`. + +Contents: 1. bundle wiring - 2. device - 3. TraceRunner - 4. tensors - 5. weights - 6. precision and knobs - +7. metrics, goldens, gates - 8. profiling - 9. I/O and outputs - 10. ModelBase - 11. server - 12. vendoring - +13. measured facts and pitfalls - 14. image pre-processing (C14) - 15. LiDAR host pipeline (C10-C12, C15, C16) - +16. CNN ops: conv builders (C17), up-sampling and interpolation (C18) - 17. attention (C20) - +18. LiDAR device modules: gather-form scatter (C19), SECOND + SECONDFPN (C24), CenterHead (C25) - +19. grid_sample helpers (C23) - 20. ResNet builders (C27) - 21. query heads: top-k (C21), heatmap peaks (C22), +TransFusion query head (C26) - 22. pillar feature net and input staging (C24 companion) - 23. segment reductions (K1) - +24. sparse-conv rulebooks (C13) - 25. gather-GEMM sparse encoder (C28). + +--------------------------------------------------------------------------------------------------------------------- + +## 1. Wiring a bundle (thin wrappers over ttaw) + +```bash +python common/tools/vendor.py bundles/-p150 # committed ttaw/ (HEAD) -> code//ttaw + VENDORED.json +python common/tools/vendor.py bundles/-p150 --check # drift report (exit 1 on drift; section 12) +``` + +`research/BUNDLE_TEMPLATE` is the canonical wiring (`instantiate_bundle.py --out` renders it and vendors ttaw; the +values file's `INPUT_KIND` picks its flavour: `lidar` as below, `camera`, `multi_camera`, `lidar_camera`, `planner` +with their own `api.py` / `io.py` / stub / smoke / tests, `research/BUNDLE_TEMPLATE/TEMPLATE_NOTES.md` "Flavours"): +`device.py` and `io.py` bind ttaw to the model, `api.py` subclasses `ModelBase`, `server/app.py` calls `create_app`, +and the stdlib `server/client.py` / `server/smoke_test.py` run `ttaw/server/{client,smoke}.py` by path: + +```python +# code//device.py: ttaw.device bound to the port's validated open parameters (the model class uses the same dict) +from .ttaw.device import DeviceConfig, close_device, describe_device # noqa: F401 +DEVICE_DEFAULTS = {"num_command_queues": 1, "l1_small_size": 32768, "trace_region_size": 64 << 20} +def device_config(**overrides): ... # DEVICE_DEFAULTS < _* / TT_DEVICE_ID < non-None overrides +def open_device(device_id=None, *, dispatch=None, **overrides): ... # device_config(...).open() + +# code//io.py: ttaw.io re-exported, decode_points / load_points rebound to the model's layout +from .ttaw.io import * # noqa: F401,F403 +DEFAULT_POINT_FIELDS = ("x", "y", "z", "intensity") + +# code//api.py (section 10 has the full hook contract) +from .ttaw.api_base import ModelBase +class CenterPoint(ModelBase): + MODEL_NAME, ENV_PREFIX = "centerpoint-p150", "CENTERPOINT" + DEVICE_DEFAULTS = device.DEVICE_DEFAULTS + ... + +# code//server/app.py (section 11) +from pathlib import Path +from ..api import CenterPoint +from ..ttaw.server.app import ServerSpec, create_app, parse_mesh_shape # noqa: F401 (tt-model.yaml verify: line) +app = create_app(ServerSpec(model_name=CenterPoint.MODEL_NAME, env_prefix="CENTERPOINT", model_cls=CenterPoint, + task="LiDAR 3D object detection", default_weights=CenterPoint.DEFAULT_REPO, + calib_dir=Path(__file__).resolve().parents[1] / "calib")) +``` + +`pyproject.toml` package data: `".ttaw" = ["API.md", "VENDORED.json"]`, `".ttaw.ops" = ["kernels/*.cpp", +"kernels/*.hpp", "kernels/*.h"]`. The tt-model `extra_code` path `` already ships the sub-package. + +--------------------------------------------------------------------------------------------------------------------- + +## 2. Device (C01, `ttaw.device`) + +```python +from .ttaw.device import DeviceConfig, describe_device, device_session, open_device, compute_grid + +with device_session(dispatch="eth", num_command_queues=2, trace_region_size=64 << 20) as dev: + print(describe_device(dev)) # {'dispatch': 'eth', 'grid': '12x10', 'cores': 120, 'num_command_queues': 2, + # 'arch': 'blackhole', 'fallback': None, 'eth_patch': True, ...} + gx, gy = compute_grid(dev) # never hard-code 12x10: program configs read the grid + +cfg = DeviceConfig.from_env("CENTERPOINT", num_command_queues=1) # _DISPATCH / _NUM_CQS / _L1_SMALL / +dev = cfg.open() # _TRACE_REGION / _WORKER_L1_SIZE, TT_DEVICE_ID +``` + +| name | signature / meaning | +|---|---| +| `open_device` | `(device_id=0, *, dispatch="eth", num_command_queues=1, l1_small_size=32768, trace_region_size=64<<20, worker_l1_size=None, allow_fallback=True)` -> ttnn device. `dispatch`: `eth` (12x10), `worker` (11x10, A/B only), `auto` (ETH if the patch marker is in `tt_metal/impl/dispatch/topology.cpp`, else WORKER + `RuntimeWarning`). A failed ETH open warns and falls back to WORKER; `allow_fallback=False` re-raises (use it in container smoke / CI). Warns if ETH does not give 12x10 | +| `DeviceConfig` | frozen dataclass of the arguments above; `.from_env(prefix, env=None, **defaults)`, `.open()` | +| `describe_device` | `(device, device_id=None)` -> dict: `dispatch` (used), `dispatch_requested`, `fallback`, `num_command_queues`, `grid` "12x10", `grid_x`, `grid_y`, `cores`, `arch`, open sizes, `eth_patch`. `dispatch="unknown"` for devices not opened by ttaw | +| `open_info(device)` | what `open_device` recorded for this device object (`{}` for a device opened elsewhere; the record is tied to the object, never to a reused `id`) | +| `close_device` / `device_session` | close (syncs first; idempotent: a second close of the same device is a no-op) / context manager that always closes | +| `resolve_dispatch(dispatch, *, home=None)`, `eth_dispatch_patch_present(home=None)`, `tt_metal_home()` | patch detection (file read; `TT_METAL_HOME`, `TT_METAL_RUNTIME_ROOT`, or the tree holding `ttnn`, found without importing it) | +| `compute_grid(dev)` / `core_grid(dev)` / `full_core_range_set(dev)` | `(x, y)` / `ttnn.CoreGrid` / one-rectangle `ttnn.CoreRangeSet` of the whole grid | +| constants | `DISPATCH_MODES`, `PATCH_MARKER`, `DEFAULT_L1_SMALL_SIZE`, `DEFAULT_TRACE_REGION_SIZE`, `P150_ETH_GRID` | + +`worker_l1_size` is absolute bytes of allocatable L1 per core; tt-metal's default is computed at open time +(about 1,461,248 B on this tree, TT_PLATFORM.md section 1). Shrinking it grows the kernel-config ring buffer. + +--------------------------------------------------------------------------------------------------------------------- + +## 3. Traces (C02, `ttaw.trace`) + +Every device stage runs inside traces. `TraceRunner` owns the persistent tensors, the warm-up, the captures, the +replays and the readback. + +```python +import ttnn +from .ttaw.trace import TraceRunner, pack_outputs + +runner = TraceRunner(device, num_command_queues=2, name="centerpoint") # CQ count defaults to the open's +runner.add_input("pillars", shape=(1, 1, 40000, 64), dtype="bfloat16") # ROW_MAJOR in DRAM by default +runner.add_input("index", init=warm_idx, dtype="uint32") # give real data if the graph gathers +runner.add_param("score_thr", 0.35) # RT-dev: fp32 [1,1,1,1] TILE +runner.add_state("prev_bev", shape=(1, 1, 22500, 256), dtype="bfloat16", pingpong=True) # temporal models + +def forward(ctx): # ctx[name]: input / param / state read buffer; no host I/O in here + x = model.backbone(ttnn.to_layout(ctx["pillars"], ttnn.TILE_LAYOUT)) + bev = model.temporal(x, ctx["prev_bev"]) + ctx.write_state("prev_bev", bev) # ttnn.copy into the state's write buffer (part of the trace) + heat = ttnn.gt(model.head(bev), ctx["score_thr"]) + return pack_outputs({"heat": heat, "boxes": model.box(bev)}) # one D2H for several outputs + +runner.add_variant("default", forward) # one trace per variant (buckets: "n8k", "n16k", ...) +runner.capture() # warm-up of every variant, then strict captures +out = runner("default", inputs={"pillars": p, "index": idx}, params={"score_thr": 0.4}) # {"heat": ..., "boxes": ...} +runner.release() # or `with TraceRunner(...) as runner:` +``` + +**What it guarantees.** Persistent tensors exist (with defined contents) before the first capture; every variant is +warmed `warmup_runs` times before *any* capture, and so are the runner's own eager programs (the `stage_inputs` +staging copy, the state <-> bank copies) and the callables registered with `add_eager_warmup(fn)`; capture runs with +`device.set_program_cache_misses_allowed(False)` +(a miss raises `... program cache miss occurred, but cache misses are forbidden` naming the op), `end_trace_capture` +runs in `finally` and a failed capture is released, and the program-cache size must not change during capture; +adding a variant after a capture releases all traces, warms the new one and recaptures everything; warm-up writes to +states are undone (`reset_state`) before capture; unchanged params are not re-uploaded. + +**No program may be compiled after the first capture.** A new program's kernel binaries are a DRAM buffer allocated +when it is first enqueued, in the address space of the traces' freed intermediates, so a replay can overwrite them +(tt-metal `tech_reports/AdvancedPerformanceOptimizationsForModels/TraceCorrectness.md`: corruption or a hang). Any +eager op the model runs between replays (host-fallback glue, an eager `ttnn.to_layout`, `tensors.upload_u8`, +`fp32_island`, ...) must therefore run once before the first capture: register it with `add_eager_warmup(fn)`. The +runner refuses its own eager work that compiles after a capture (`stage_fn` copies, `save_state` / `load_state`, +`reset_state` from a device tensor of another spec, `run_eager`) with `RuntimeError: ... compiled a new program after +capture`, and every port runs its device tests once with `TT_METAL_TRACE_ALLOC_TRACKING=1` (the tracker refuses a +replay while such a buffer is alive; ttaw 0.2.0's `stage_inputs` path tripped it: +`logs/ttaw/review_old_staged_tracking_probe.log`). + +**1CQ / 2CQ.** 1CQ: uploads and replays on CQ0. 2CQ: CQ1 waits for the last replay's event, uploads, records; CQ0 +waits, replays, records (the `check_dispatch.py` pattern; the events exist even after a partially failed `capture()` +left some variants runnable). `stage_inputs=True` (2CQ only) is the `tt_cnn` executor +pattern: CQ1 writes DRAM staging copies while the previous replay still runs, an eager `ttnn.copy` (or your +`add_input(..., stage_fn=lambda staging, dst: ...)`, e.g. a reshard into a sharded L1 input) moves them into the +trace inputs on CQ0; that copy is compiled in the first `capture()` (a staging buffer mirrors every +`write_input`). `read(variant, cq_id=1)` (2CQ) waits for that trace's completion event on the host and reads on CQ1, +so CQ0 can already run the next segment. + +**Segments.** Split a long graph into variants run back to back; hand intermediates from segment k to k+1 through an +in-place state (`ctx.write_state("mid", t)` in seg1, `ctx["mid"]` in seg2): a variant cannot see another variant's +outputs at warm-up time, a state buffer exists from the start. + +**Ping-pong state.** `pingpong=True` allocates two buffers and captures two traces per variant (phase 0 reads A / +writes B, phase 1 the reverse). A variant that writes the ping-pong states must write all of them ("stepping"); the +phase flips after each run of a stepping variant; read-only variants follow the current phase. In-place states +(default) read and write one buffer, so read what you need before the write. Reset with `reset_state(name, value)` +(host data, or a device tensor copied on the device). `write_state` traces one `ttnn.copy`; compute the new state +straight into `ctx.write_target(name)` (`ttnn.add(old, x, output_tensor=ctx.write_target("mem"))`, then +`ctx.write_state("mem", new)`) and no copy is traced (probe P13: one program less per state per frame). +`write_state` / `write_output` check shape, layout (ttnn.copy keeps it) and dtype changes (TILE only) before tracing. +For a ring buffer use `ttnn.copy` / slices into a fresh tensor and `write_state`; `ttnn.experimental.slice_write` +into a TILE state re-binds the handle and breaks traces (probe P13). + +**Per-stream state (PLAN.md D16).** A trace bakes one set of state addresses, so several `stream.id`s share them: +`add_state(..., banks=S_MAX)` allocates `S_MAX` DRAM banks of the state before capture, `save_state(name, i)` / +`load_state(name, i)` copy between the state and bank `i` (eager `ttnn.copy` on CQ0, ordered after the enqueued +replays; ~80 us for a StreamPETR-size state), and `StreamBanks` is the policy every temporal bundle uses: + +```python +from .ttaw.trace import StreamBanks +runner.add_state("prev_bev", shape=(1, 1, 22500, 256), dtype="bfloat16", pingpong=True, + banks=S_MAX if S_MAX > 1 else 0) # S_MAX = 1 at the first publish +streams = StreamBanks(runner, ["prev_bev"], max_streams=S_MAX, on_full="reject", max_gap_s=2.0) +fresh = streams.select(stream.get("id", "default"), reset=stream.get("reset", False), + timestamp_s=stream.get("timestamp_s")) # in _prepare, under the model lock +params = {"use_prev_bev": 0.0 if fresh else 1.0} # first-frame RT-dev params +``` + +`select` returns True when the stream starts fresh (new id, `reset=True`, timestamp backwards or a gap above +`max_gap_s`) after resetting its states to `init`; a new id beyond `max_streams` raises `InputError` (HTTP 400) with +`on_full="reject"` or takes the least recently used stream's bank with `"evict"` (`S_MAX=1`: restart the one state). +`forget(id)`, `streams` (most recent first), `active`, `describe()` (for `model.info`). + +**Outputs.** A variant returns either the tensors its last ops produce (allocated during the capture, alive as long +as the trace) or persistent outputs: `add_output(name, shape=...)` allocates a buffer before any capture and +`ctx.write_output(name, value)` copies into it inside the trace and returns it. Persistent outputs keep their address +across recaptures, can be shared by several variants (shape buckets with one readback) and are never overwritten by +another variant's replay; they cost one `ttnn.copy` per output. Op-produced outputs of a variant captured later can +be overwritten when an earlier-captured variant replays: read them before running another variant (`read` and +`__call__` return copies), and give segments read on CQ1 while CQ0 already replays the next one persistent outputs. +Warm-up and release free op outputs without `force`, so an output that shares memory with something the runner +does not own (a view of a weight) is never freed by the runner. + +| `TraceRunner` member | signature / meaning | +|---|---| +| constructor | `TraceRunner(device, *, num_command_queues=None, warmup_runs=1, stage_inputs=False, forbid_cache_misses=True, alloc_tracking=None, name="model")` | +| `add_input` | `(name, init=None, *, shape=None, dtype="bfloat16", layout=ROW_MAJOR, memory_config=DRAM, stage_fn=None)` -> device tensor. `init`: numpy / torch / ttnn host tensor (warm-up data), else zeros | +| `add_param` | `(name, value=0.0, *, shape=(1,1,1,1), dtype="float32", layout=TILE, memory_config=DRAM)` -> device tensor; broadcasts in ttnn binary ops | +| `add_state` | `(name, init=None, *, shape=None, dtype="float32", layout=TILE, memory_config=DRAM, pingpong=False, banks=0)` -> buffer or (A, B) | +| `add_output` | `(name, *, shape, dtype="float32", layout=TILE, memory_config=DRAM)` -> persistent output buffer (zeros) | +| `add_variant` | `(name, fn, *, warmup_runs=None)`; `fn(ctx)` returns a device tensor, a `Packed`, or a list / tuple / dict of them | +| `add_eager_warmup` | `(fn)`: eager device work the model runs between replays; `fn()` runs in the first `capture()`, before any trace (refused after it) | +| `capture()` | warm-up + capture of all pending variants (idempotent) | +| `run(variant=None, inputs=None, params=None)` | upload + non-blocking replay; returns the device outputs | +| `read(variant=None, *, cq_id=0, as_torch=False, leaves=None)` | blocking read into preallocated host tensors -> numpy (or torch); `Packed` -> `{name: array}`; `leaves` (0.24.3): indices of the output leaves to read (flattened order), the others None with no transfer; the rest of the same run can be read later while `runs` is unchanged | +| `__call__(variant=None, inputs=None, params=None, *, as_torch=False, leaves=None)` | `run` + `read` (`leaves`: the partial read, 0.24.3) | +| `upload(inputs=None, params=None)` / `replay(variant=None, n=1)` | the two halves of `run` (benches, pipelining) | +| `run_eager(variant=None, inputs=None, params=None)` | same function without a trace, buffers freed before returning: replay-vs-eager bit checks | +| `set_params(**values)` / `write_input(name, value)` | queue param values for the next run / upload an input now (CQ0; with 2 CQs the event the next CQ1 upload waits for is re-recorded after it) | +| `reset_state(name=None, value=None)` / `read_state(name)` / `state_buffer(name)` / `phase` | state control (on CQ0, ordered after enqueued replays); `value` may be a device tensor | +| `save_state(name, bank)` / `load_state(name, bank)` | state <-> bank copies on CQ0 (`add_state(banks=...)`; D16) | +| `outputs(variant=None, phase=None)`, `trace_ids()`, `describe()`, `timings_ms`, `phases`, `captured`, `runs` (0.24.3: replays so far) | introspection (`describe()` is JSON-able: put it in `model.info`) | +| `release()` | release traces and persistent tensors (idempotent; also `__exit__`) | + +`TraceContext` (the `ctx` of a variant): `ctx[name]` (input, param, persistent output, or a state's read buffer), +`ctx.state(name)`, `ctx.write_target(name)`, `ctx.write_state(name, value)`, `ctx.write_output(name, value) -> +buffer`, `ctx.variant`, `ctx.phase`, `ctx.capturing`, `ctx.device`. Registering inputs / states / variants from +inside a variant function (during warm-up or capture) raises. + +`StreamBanks(runner, states, *, max_streams=1, on_full="reject", max_gap_s=None)`: `.select(stream_id, *, +reset=False, timestamp_s=None) -> fresh`, `.forget(id)`, `.streams`, `.active`, `.describe()` (above). + +`pack_outputs(tensors: dict, *, dtype="float32", align=32, row_elems=None) -> Packed`: one ROW_MAJOR tensor holding +every output (typecast to `dtype`; float32 is exact for bf16 and integers < 2**24), read with ONE device-to-host copy; +`TraceRunner.read` unpacks it, `Packed.layout.unpack(flat)` gives `{name: array}` (views) from any array of +`layout.total` elements (`PackLayout(entries, total, rows, row_elems)`, `.shape` = the device shape; `PackEntry(name, +offset, numel, shape, pitch=0)` indexes the elements in row-major order; `pitch > 0`: the tensor's rows of +`shape[-1]` elements are stored `pitch` elements apart, zero-padded, and `unpack` / `entry.view(flat)` return a +strided view). Layout (since 0.15.0, YOLOX PORT_LOG Q9): + +- packed total <= `SINGLE_ROW_MAX_ELEMS` (131072 = 512 KiB of fp32): one `[1, 1, 1, total]` row, each tensor + flattened and zero-padded to `align` elements -- exactly the layout and programs of 0.1.0-0.14.0; +- above it, or with `row_elems=R` (a multiple of 32): `[1, 1, rows, R]`, R = `PACK_ROW_ELEMS` (1024) by default. + Each tensor starts on a row boundary and is zero-padded to whole rows (a tensor of at most 64 KiB is flattened + and padded by < R elements; a larger `[.., n, c]` gets zero rows appended until `n * c` fills whole rows of R, + i.e. n rounded up to a multiple of `R / gcd(c, R)`; when that wastes more than 1/8 of the tensor beyond the best + alternative -- few rows of an awkward width: 0.15.0-0.18.0 packed `[1, 1, 2, 20001]` fp32 as 80 MB -- it is + flattened if its padded row fits 128 KiB, else its rows are zero-padded to a pitch `p` = c rounded up to a power + of two dividing R, or to R, the smallest segment: one `ttnn.pad` of the row and last dims, then the reshape into + rows of R; segments stay below 1.4x the tensor + one row, typical shapes keep the contiguous layout), then the + segments are concatenated on the row dim. No ROW_MAJOR page above 128 KiB is reshaped, so outputs of tens of MB + pack; a flat vector `[1, 1, 1, N]` wider than that is cut into `ttnn.slice` chunks; any other tensor with rows + wider than 128 KiB raises `ValueError` (give it a narrower last dim). Measured (p150b, + `tests/device/test_pack_outputs_device.py`, two runs, 1CQ / 2CQ; pack = replay of the packing trace, read = D2H + + unpack): 64 KB single row 0.15-0.22 + 0.14-0.18 ms; 1 MB (YOLOX 14400 x 13 fp32 head level + a 240 x 240 uint32 + map) 0.69-0.75 + 0.30-0.54 ms; 16 MB (`[1, 1, 262144, 16]` fp32) 1.24-1.74 + 3.7-8.1 ms (2-4 GB/s); bit-exact + through trace replays (`logs/ttaw/q9_pack_outputs_device*.log`). + Why: a single ROW_MAJOR row is ONE page, and `ttnn.reshape` / `concat` stage whole pages in L1 (2 x the + destination page per kernel copy for pages that are not 16-byte aligned), so the 0.14.0 layout failed above + ~0.6 MB with `TT_FATAL: RM reshape dest staging does not fit in L1`. + +`CQ_COMPUTE = 0`, `CQ_INPUT = 1`. + +**Alloc tracking (debug).** `TT_METAL_TRACE_ALLOC_TRACKING=1` must be exported before Python imports ttnn; then +`ttnn.execute_trace` refuses to replay while a buffer allocated after a capture is alive. `alloc_tracking_enabled()` +reports it; `TraceRunner(alloc_tracking=True)` raises if it is off. The runner acknowledges the outputs of every trace +captured after the first (plain ttnn would flag them: `tests/device/test_trace_alloc_tracking_device.py`). + +--------------------------------------------------------------------------------------------------------------------- + +## 4. Tensors (C03, `ttaw.tensors`) + +| name | meaning | +|---|---| +| `TILE`, `round_up(n, multiple=32)`, `tile_padded_shape(shape)`, `pad_to_tile(a, value=0)` | tile geometry (host) | +| `pad_to_capacity(a, capacity, *, axis=0, value=0, truncate=False) -> (padded, n_valid)` | fixed-capacity buffers (capacities are grid-independent constants) | +| `as_4d(a)` | prepend unit dims to rank 4 | +| `float32_to_bf16_bits`, `bf16_bits_to_float32`, `round_to_bf16` | RNE bf16 conversion identical to torch (expected values for exact tests) | +| `ttnn_dtype(name)`, `dtype_name(dtype)` | `"bf16"`, `"fp32"`, `"bfp8"`, `"bfp4"`, `"uint32"`, `"int32"`, `"uint16"`, `"uint8"` aliases | +| `to_host_tensor(value, dtype, layout=None, *, shape=None)` | numpy / torch / ttnn host tensor -> ttnn host tensor; integers never pass through a float intermediate (int64 input to `ttnn.from_torch` would) | +| `to_device(value, device, dtype="bf16", layout=None (TILE), memory_config=None (DRAM))` | eager upload | +| `to_numpy(t)` | ttnn (device or host) / torch -> numpy (bf16 -> float32) | +| `to_layout(t, layout)`, `typecast(t, dtype)`, `to_fp32(t)`, `to_bf16(t)` | no-ops when nothing changes (no extra program) | +| `fp32_island(fn, *tensors, out_dtype="bfloat16")` | run `fn` on fp32 copies, cast results back | +| `upload_u8(array, device, *, out_dtype="bfloat16", layout=None, memory_config=None)` | uint8 upload + on-device typecast (exact); in a trace keep the uint8 tensor as the input and `ttnn.typecast` as the first op | +| `HostStaging(shape, dtype)` | persistent ROW_MAJOR host tensor; `.write(array)` copies into its buffer through a `torch.from_dlpack` alias (`zero_copy=True` on this tree for float32 / bfloat16 / uint32 / int32 / uint16 / uint8) and returns `.tensor`; pass it as a `run(inputs=...)` value | + +--------------------------------------------------------------------------------------------------------------------- + +## 5. Weights (C04, `ttaw.weights`) + +```python +from .ttaw.weights import OnnxWeights, WeightCache, fold_bn_conv + +w = OnnxWeights(weights_path / "pts_backbone_neck_head_centerpoint.onnx") # parsed as data, never executed +for node in w.nodes("Conv", "/backbone/*"): # graph order, glob or regex + wf, bf = w.fold_conv_bn(node.name) # + its BatchNormalization consumer, fp64, rounded once +k = w.param("/dit/blocks.0/attn/MatMul", 1) # anonymous initializer, addressed by consuming node + slot +cache = WeightCache("tt_centerpoint/base", w.sha256, version=f"{__version__}.prep1") # $TT_CACHE_PATH | ~/.cache/ttaw +tw = cache.get("backbone.0.conv.w", lambda: wf, dtype="bfloat16", layout=ttnn.ROW_MAJOR_LAYOUT, device=dev) +``` + +| name | meaning | +|---|---| +| `OnnxWeights(path, *, load_external_data=True)` | `.array(name)` (initializer / Constant, through Identity), `.has`, `.initializer_names()`, `.state_dict()`, `.node(name)`, `.nodes(op_type=None, pattern=None, *, regex=False)`, `.find_node(pattern, op_type=None, *, regex=False)`, `.producer(t)`, `.consumers(t)`, `.consumer_of(t, op_type=None)`, `.param(node, slot)`, `.params(node)`, `.conv(node) -> ConvParams`, `.gemm(node) -> GemmParams`, `.matmul_weight(node)`, `.batchnorm(node) -> BatchNorm`, `.fold_conv_bn(conv, bn=None, *, dtype=np.float32)`, `.sha256`, `.input_names`, `.output_names`, `.opset`. External data outside the model directory is refused. Unnamed nodes are `"_"` | +| `OnnxNode`, `ConvParams` (weight, bias, strides, pads, dilations, group, kernel_shape, output_padding, auto_pad, output_shape), `GemmParams` (weight as stored, bias, trans_a, trans_b, alpha, beta) | frozen records; `pads` is the explicit attribute: with `auto_pad` `SAME_*` derive the padding from the input size | +| `BatchNorm(gamma, beta, mean, var, eps=1e-5)` | float64; `.scale`, `.shift`, `.channels`, `.apply(x, axis=1)`, `.from_state_dict(sd, prefix, eps)` | +| `fold_bn(w, b, bn, *, axis=0, dtype=np.float32)` | generic fold (`dtype=None` keeps float64 for a single final rounding to the device dtype) | +| `fold_bn_conv(w, b, bn)` | Conv weight `[Cout, Cin/g, k...]`, any groups | +| `fold_bn_linear(w, b, bn, *, layout="out_in")` | torch Linear / Gemm transB=1 (`out_in`) or MatMul / Gemm transB=0 (`in_out`); also BN1d | +| `fold_bn_conv_transpose(w, b, bn, *, groups=1)` | ConvTranspose weight `[Cin, Cout/g, k...]` | +| `load_safetensors(path)`, `load_torch_checkpoint(path, *, key=None)` (`torch.load(weights_only=True)`), `load_state_dict(path)` -> `StateDict` | `.safetensors`, `.pth/.pt/.ckpt/.bin`, `.npz` | +| `StateDict(tensors)` | `.sub(prefix)`, `.strip(prefix)`, `.bn(name, eps)` | +| `WeightCache(namespace, source_digest="", *, version="", root=None, enabled=None)` | `.get(key, make, *, dtype, layout=None, device=None, memory_config=None, shape=None)` caches ttnn host tensors as `.tensorbin` (atomic writes; rebuilt if unreadable or of another dtype / layout / `shape`), `.path(...)`, `.clear()`, `.hits`, `.misses`; `TTAW_WEIGHT_CACHE=0` disables. The cache outlives images (`/tensor-cache` is the host's `~/.cache/tt-model//tensors`): pass `version` (bundle `__version__` + a prep revision) and bump it whenever the code that prepares the tensors changes | +| `cache_root()`, `file_sha256(path)` | helpers | + +--------------------------------------------------------------------------------------------------------------------- + +## 6. Precision and knobs (C05, `ttaw.precision`, `ttaw.knobs`) + +`ttnn.matmul` / `linear` drop to LoFi when a `program_config` or `core_grid` comes without a compute config, and +`ttnn.WormholeComputeKernelConfig()` without `math_fidelity` is `MathFidelity.Invalid`. Always pass one: + +```python +from .ttaw.precision import PrecisionPolicy, compute_kernel_config +POLICY = PrecisionPolicy({"head.reg*": "accurate", "backbone.*": "HiFi2+fp32:w=bfp8"}, default="balanced") +policy = POLICY.with_env("CENTERPOINT") # CENTERPOINT_PRECISION="backbone.*=HiFi4+fp32;*=HiFi2+fp32" +y = ttnn.linear(x, w, compute_kernel_config=policy.compute_kernel_config("head.reg.fc1"), program_config=pc) +w_dtype = policy.resolve("backbone.block3.conv2").weights_dtype() +``` + +| name | meaning | +|---|---| +| `compute_kernel_config(fidelity="HiFi2", *, fp32_acc=True, approx=False, packer_l1_acc=False, dst_full_sync=False)` | explicit `ttnn.WormholeComputeKernelConfig` (= `BlackholeComputeKernelConfig`) | +| `Precision(fidelity="HiFi2", fp32_acc=True, approx=False, packer_l1_acc=False, dst_full_sync=False, weights="bfloat16", activations="bfloat16")` | `.parse("HiFi4+fp32+approx+l1acc+fullsync:w=bfp8:a=bf16" or preset)`, `.label`, `.with_(**)`, `.compute_kernel_config()`, `.weights_dtype()`, `.activations_dtype()` | +| `PRESETS` | `accurate` (HiFi4 + fp32), `balanced` (HiFi2 + fp32, the default), `fast` (LoFi, bfp8 weights; only after gates pass) | +| `PrecisionPolicy(rules, default="balanced")` | first matching glob wins; `.resolve(module)`, `.compute_kernel_config(module)` (cached), `.override(spec)`, `.with_env(prefix, env=None)`, `.describe()` (rules + which modules resolved to what) | +| `FIDELITIES` | `("LoFi", "HiFi2", "HiFi3", "HiFi4")` | + +Other silent defaults to override by hand: `ttnn.layer_norm` epsilon 1e-12, SDPA `is_causal=True`, `ttnn.embedding` +PADDED returning the cached pad row, HARDSWISH fused into conv2d skipped. + +Knobs (one per optimization, default = measured best, pinned in `tt-model.yaml serve.env`): + +```python +from .ttaw.knobs import Knob, Knobs +KNOBS = Knobs("CENTERPOINT", [Knob("FUSED_HEAD", True, "merged head convs"), + Knob("ACT_BLOCK_H", 64, "conv act_block_h", choices=(32, 64, 128)), + Knob("BFP8_WEIGHTS", False, "bfp8 backbone weights", experiment=True)]) +knobs = KNOBS.read() # once, in _build; env CENTERPOINT_FUSED_HEAD=0 is the A/B switch +assert KNOBS.serve_env() == yaml_serve_env_subset # host test: the image pins the defaults +``` + +`Knob(name, default, doc="", choices=None, experiment=False)`; `Knobs(prefix, knobs)`: `.read(env=None, +**overrides) -> KnobValues` (attribute / item access, `.source(name)`, `.overridden()`, `.as_dict()`, immutable; +warns when an experiment knob is set), `.defaults()`, `.serve_env(values=None)`, `.doc_table()`, `.env_name(name)`; +`parse_bool(text)`. + +--------------------------------------------------------------------------------------------------------------------- + +## 7. Metrics, goldens, gates (C06, `ttaw.metrics`, `ttaw.golden`) + +```python +# tests/test_pcc_device.py of a bundle +from ..ttaw.golden import GateRegistry, compare_taps, load_goldens +from ..ttaw.metrics import pcc, match_detections + +GATES = GateRegistry.for_test(__file__, {"backbone": 0.999, "head.heatmap": 0.99, + "dets.recall": (0.95, "min", "recall"), "plan.ade": (0.5, "max", "ade")}) + +def test_taps(device_taps): # numpy dict from an eager device run or trace outputs + with load_goldens(SPEC_DIR / "golden/sample0.npz") as gold: + report = compare_taps(device_taps, gold, gates=GATES, names=["backbone", "head.heatmap"]) + report.save_json(LOGS / "compare_backbone.json"); print(report.table()) + assert report.passed +``` + +`GateRegistry` stores frozen gates in `.gates.json` next to the test at the first green run. A later +declaration that is looser (lower `min`, higher `max`, other direction or metric) raises `GateLoosenedError`; +tighter ones are re-frozen; failing checks freeze nothing. `TTAW_GATES_READONLY=1` (or `write=False`) never writes. +Changing a frozen gate = editing the JSON by hand + disclosure in VERIFICATION_.md. + +| name | meaning | +|---|---| +| `pcc(t, r)` | float64 Pearson; NaN on non-finite input; a constant side (detected exactly, max == min) gives 1.0 for two equal constants (`np.allclose`) and 0.0 otherwise, also for two different constants | +| `masked_pcc(t, r, mask)`, `valid_row_pcc(t, r, n_valid=None, *, rows=None, axis=0)` | padded / masked buffers | +| `error_stats(t, r)` | `{pcc, max_abs, mean_abs, rel_l2, n}` | +| `argmax_agreement(t, r, *, axis=-1, mask=None)`, `label_agreement(t, r, *, mask=None)` | class decisions (ties -> lowest index) | +| `mask_iou(a, b)`, `mean_iou(t, r, num_classes, *, ignore_index=None) -> (miou, per_class)`, `box_iou_xyxy(a, b)` | IoU | +| `topk_overlap(t_idx, r_idx, k=None)`, `topk_set_overlap(t_scores, r_scores, k)` | data-dependent selections | +| `match_detections(t_centers, t_labels, t_scores, r_centers, r_labels, r_scores, *, max_dist=0.5, dims=2, same_label=True) -> DetectionMatch` | greedy same-label BEV-centre matching (`.pairs`, `.recall`, `.precision`, `.matched`, `.center_errors`, `.score_errors`, `.to_dict()`); box arrays `[N, 7]` work as centres; a box with a non-finite centre never matches | +| `ade_fde(pred, ref, *, dims=2) -> (ade, fde)` | trajectories `[..., T, D]` | +| `as_array(x)` | numpy / torch (bf16 ok) / list -> numpy | +| `save_goldens(path, tensors, meta=None, *, compress=False)`, `load_goldens(path) -> Goldens` | `.npz` + JSON `__meta__`; `Goldens` is a lazy mapping with `.meta`, `.sha256`, `.close()`, context manager | +| `TapRegistry(enabled=True, *, include=("*",), exclude=())` | `.tap(name, value) -> value` (device tensors read at once; raises inside a capture), `.scope(prefix)`, `.wants`, `.names()`, `.to_dict()`, `.save(path, meta)`, `.clear()`; `NULL_TAPS` is a disabled registry | +| `Gate(threshold, direction="min", metric="pcc")` | `.of(spec, metric=None)` (a bare number takes the direction of `metric` from `DIRECTIONS` and is refused for a metric of unknown direction; a direction contradicting a known metric, e.g. a `"max"` PCC gate, is refused), `.passes(v)` (NaN fails), `.looser_than(other)` | +| `GateRegistry(path, gates=None, *, write=None)` | `.for_test(test_file, gates)`, `.check(name, value, gate=None) -> GateResult`, `.require(...)` (AssertionError), `.gate(name)`, `.names()`, `.frozen`, `.results`, `.save()` | +| `CompareReport(title="", meta=None, gates=None)` | `.add(name, test, ref, *, metric="pcc", gate=None)`, `.add_value(name, value, *, metric, gate=None, stats=None)`, `.passed`, `.table()`, `.to_dict()`, `.save_json(path)`; `TapComparison` records | +| `compare_taps(test, golden, *, gates=None, metric="pcc", names=None, title="", meta=None)` | one report over common (or named) taps; missing taps fail when gated | +| `METRICS` | name -> (function, direction) used by reports (`pcc`, `masked_pcc`, `argmax_agreement`, `label_agreement`, `mask_iou`, `max_abs`, `mean_abs`, `rel_l2`) | +| `DIRECTIONS` | metric name -> `"min"` / `"max"` for every gate metric that may be given as a bare number: the `METRICS` plus `recall`, `precision`, `iou`, `miou`, `agreement`, `topk_overlap` (min) and `ade`, `fde`, `center_err*`, `score_err*`, `max_abs_err` (max) | + +--------------------------------------------------------------------------------------------------------------------- + +## 8. Bench and profile (C07, `ttaw.profiling`) + +```python +from .ttaw.profiling import AiclkSampler, bench_trace_runner, signposted, summarize_ops + +with AiclkSampler(interval_s=0.05) as clk: # sysfs tt_aiclk + hwmon power / temperature + bench = bench_trace_runner(model.runner, "default", {"pillars": p}, iters=100, post=model.decode) +bench.save_json(f"{ROOT}/logs/centerpoint/bench_baseline.json", config=model.device_info, aiclk=clk.summary()) +print(bench.table()) # host_in / h2d / trace / d2h / post / e2e / b2b, p50 p99 + +with signposted("trace"): # profile_ops.py under `python -m tracy -r -p -v -o ...` + model.runner.replay("default"); ttnn.synchronize_device(dev) +print(summarize_ops(f"{ROOT}/generated/profiler/centerpoint_baseline").table()) # ops, kernel sum, op2op, span +``` + +| name | meaning | +|---|---| +| `StageBench(name="")` | `.stage(name)` context, `.add(name, ms)`, `.summary()` (`{stage: {n, p50, p99, mean, min, max}}`), `.table()`, `.to_dict(**extra)`, `.save_json(path, **extra)`; `STAGES` order | +| `bench_trace_runner(runner, variant, inputs, *, params=None, iters=100, warmup=10, post=None, b2b_iters=None, name="")` | the standard stage breakdown of a `TraceRunner` variant | +| `time_b2b(enqueue, sync, n=100, warmup=5) -> ms` | back-to-back device time per iteration | +| `signpost(name, message=None) -> bool`, `signposted(name)` | Tracy markers (no-op without `tracy`) | +| `read_device_profiler(device)` | `ttnn.ReadDeviceProfiler` per trace segment (the buffer holds ~1000 ops) | +| `summarize_ops(source, *, start="trace", end=None, last_replay_session=None, freq_mhz=None, top_gaps=10) -> OpsSummary` | `ops_perf_results*.csv` / `cpp_device_perf_report.csv` / directory / rows; `OpsSummary`: `ops`, `kernel_sum_us`, `fw_sum_us`, `op2op_sum_us`, `span_us`, `by_op`, `fidelity`, `top_gaps`, `.table(top)`, `.to_dict()`. CLI: `python -m .ttaw.profiling [--start trace] [--end trace_end] [--json out]` | +| `find_ops_csv(path)` | newest ops CSV under a directory | +| `AiclkSampler(chip=0, interval_s=0.05, *, root="/sys/class/tenstorrent")` | `.start()`, `.stop()`, context manager, `.sample_once()`, `.summary()`, `.available` | + +`common/tools/p2_trace_bench.py --mode eth-1cq|eth-2cq|eth-2cq-staged|worker-2cq` measures the runner itself. + +--------------------------------------------------------------------------------------------------------------------- + +## 9. I/O and outputs (C08, `ttaw.io`, `ttaw.outputs`) + +`ttaw.io` (numpy only; every client mistake raises `InputError`, which the server maps to HTTP 400): +`b64decode(s, *, field, max_bytes)`, `PointCloud(points, fields, frame_id)` (`.select(names, fill=None)`; rows with a +non-finite `x` / `y` / `z` column -- the first three columns when unnamed -- dropped), +`decode_points(spec, *, max_points=2_000_000, max_bytes=None, default_fields=DEFAULT_POINT_FIELDS)`, +`load_points(source, *, fields=None, fmt=None, frame_id="base_link", default_fields=...)` (path `.bin/.npy/.npz/.pcd`, +bytes + `fmt`, arrays, structured arrays, envelopes), `decode_image(raw, *, fmt="auto", max_side=8192)`, +`load_image(image)` -> RGB uint8 HxWx3, `CameraImage`, `decode_cameras(images, calibration=None, *, order=None, +require_calibration=True, max_bytes=None)` (the server's `images[]`), its Python-API twins (0.15.0) +`load_camera(source, *, name=None, calibration=None, require_calibration=False)` (a `CameraImage`, `{"camera", +"image" | "path" | "data", "intrinsics", "T_ref_from_camera", "distortion", "timestamp_s"}` or any `load_image` source +with `name`; inline calibration wins over `calibration["cameras"][name]`) and `load_cameras(images, calibration=None, +*, order=None, require_calibration=True, calib_dir=None)` (a list or a `{name: image}` mapping; `{"preset": name}` +resolved in `calib_dir`; reordered to `order`, every camera exactly once: `model(images=..., calibration=...)` and +`/predict` see the same cameras), `decode_rois(rois, *, cameras=None, labels=None, max_rois=4096)` (2-D detections +as an input, `[{"camera", "label", "score", "box_xyxy"}]`: names / indices checked against `labels`, score in [0, 1], +finite ordered boxes; PointPainting `rois`, BUNDLE_CONVENTIONS.md 7.2), `parse_transform(obj, *, field)` (4x4 / 3x4 / `{matrix}` / +`{translation, rotation_wxyz|rotation_xyzw|rotation}` / `{x, y, z, roll, pitch, yaw}` tf2 RPY), +`parse_intrinsics(obj, *, field)`, `resolve_calibration(calibration, calib_dir)` (`{"preset": name}` -> +`calib_dir/.json` merged), `decode_named_arrays(spec, schema=None, *, max_bytes=None)` (planner inputs), +`check_named_arrays(arrays, schema)` (names, shapes, numeric and finite values, integral values in range for integer +dtypes; every problem is an `InputError`), `load_named_arrays(source, schema=None)` (mapping / envelope / `.npz` +path or bytes: the Python-API form), +`encode_array(arr, *, fmt="npz"|"npz_compressed"|"raw"|"list", key)`, `encode_png(image, *, key)`, `to_jsonable(obj)` +(float32 / float16 scalars rounded to 6 significant digits, float64 exact), +`POINT_FORMATS`, `DEFAULT_POINT_FIELDS = ("x", "y", "z", "intensity")`, `MAX_POINTS_DEFAULT`. + +`ttaw.outputs` (each has `to_dicts()` and `to_dict(output_format="json"|"npz")` = the `/predict` body with `model`, +`frame_id`, `meta`, `timing_ms`): + +| class | fields | +|---|---| +| `Detections3D(boxes [N,7] x y z l w h yaw, scores, label_ids, velocities=None, labels=(), model="", frame_id="base_link", timing_ms, meta)` | rows sorted by score at construction; `detections[] {label, label_id, score, center, size, yaw, velocity}`; npz adds `arrays` | +| `Detections2D(boxes_xyxy, scores, label_ids, labels=(), extras={}, model, frame_id="camera", ...)` | `detections[] {label, label_id, score, box_xyxy}`; `extras` (e.g. `{"semseg": Mask2D}`) encoded by name | +| `Segmentation3D(label_ids [N], class_names=(), scores=None, ...)` | `labels` (npz uint8 / uint16), `class_names`, `class_counts`, `scores` | +| `Mask2D(mask (H, W), class_names=(), encoding="png", ...)` | `mask` (png, or npz for `output_format="npz"` / non-uint8), `class_counts`; `.payload(fmt)` | +| `Trajectory(poses [T, D], columns=("x", "y", "yaw"), turn_indicator=None, predicted_agents=None, ...)` | `trajectory`, `columns`, `num_poses`, `turn_indicator`, `predicted_agents` (npz) | + +`label_name(labels, id)` maps ids to names (the id as text when out of range). + +--------------------------------------------------------------------------------------------------------------------- + +## 10. `ModelBase` (C08, `ttaw.api_base`) + +```python +from .ttaw.api_base import ModelBase +from .ttaw.outputs import Detections3D + +class CenterPoint(ModelBase): + MODEL_NAME = "centerpoint-p150"; ENV_PREFIX = "CENTERPOINT" + DEFAULT_REPO = "AutowareFoundation/lidar_centerpoint"; DEFAULT_TAG = "v4.1" + DEFAULT_REVISION = "494c8171def40bd36cc2feb323e0a5acbfab132b"; ALLOW_PATTERNS = ["base/*", "tiny/*"] + VARIANTS = ("base", "tiny"); DEFAULT_VARIANT = "base"; INPUT_KIND = "lidar" + LABELS = ("CAR", "TRUCK", "BUS", "BICYCLE", "PEDESTRIAN") + RUNTIME_PARAMS = {"score_threshold": (float, 0.0, 1.0, 0.35), "max_detections": (int, 1, 1000, 500)} + DEVICE_DEFAULTS = {"num_command_queues": 1, "trace_region_size": 64 << 20} + + def _build(self): # weights -> device tensors, TraceRunner + inputs / params / states / variants + self.runner = TraceRunner(self.device, name=self.MODEL_NAME); ... + def _warm_one(self, v): # capture (default_warmup_variants() -> [{"variant": self.variant}]) + self.runner.capture() + def _prepare(self, points=None, **kw): # host pre-processing; raise io.InputError for client mistakes + ... + def _forward(self, prep): # under the model lock + return self.runner("default", inputs={...}) + def _postprocess(self, raw, prep, params) -> Detections3D: + return Detections3D(boxes, scores, ids, labels=self.LABELS, model=self.MODEL_NAME) + def _release(self): + self.runner.release() + def extra_info(self): + return {"trace": self.runner.describe(), "knobs": self.knobs.as_dict()} + +with CenterPoint.from_pretrained() as model: # weights (pinned) -> device (ETH, 12x10) -> build -> warm + out = model("samples/test.npz", score_threshold=0.4) + print(out.to_dict()["num_detections"], out.timing_ms, model.info) +``` + +`from_pretrained(model_id=None, *, revision=None, variant=None, device_id=None, device=None, dispatch=None, +num_command_queues=None, weights_dir=None, warmup_variants="default", verbose=False, **compile_params)`: weights are +resolved first (`weights_dir` > `_WEIGHTS_DIR` > local dir `model_id` > HF snapshot at the pinned revision, +offline fallback to the cache), then the device opens with `DEVICE_DEFAULTS` < `_*` / `TT_DEVICE_ID` < explicit +arguments; a caller-provided `device` is left open by `close()`. Variant default: `_VARIANT` or +`DEFAULT_VARIANT`. A failing build closes everything. + +Other members: `resolve_weights(...)` (also module-level `resolve_weights(model_id, *, revision, allow_patterns, +weights_dir, env_var)`), `device_config(**overrides)`, `requires_calibration()`, `validate_params(params)` (unknown / +outside `[min, max]` (either bound may be None) / wrong type -> `InputError`; bools must be real booleans, ints must +be integral and not booleans, floats finite; numeric strings are accepted), `warmup(variants="default")` (idempotent), +`default_warmup_variants()`, `__call__(points=None, *, sweeps, images, calibration, stream, inputs, **params)` / +`predict` (one re-entrant lock around prepare + forward + postprocess; fills `timing_ms` preprocess / device / +postprocess / total), `info`, `closed`, `close()` (idempotent, also at interpreter exit), context manager. +Class attributes also: `WEIGHTS_LICENSE`, `CAMERA_ORDER`, `REQUIRE_CALIBRATION` (None: true for multicam), +`POINT_FIELDS`, `EXTRA_INPUTS` (model-specific input keywords handed to `_prepare` instead of being validated as +runtime params, e.g. PointPainting `("rois",)`; the server's `decode_extra` adds them to the call kwargs) and +`INPUT_SCHEMA` (`{name: (shape with None for free dims, dtype)}`: `inputs=` is decoded with +`io.load_named_arrays` and checked on every call, API and server alike). `RUNTIME_PARAMS` may not reuse an input +keyword (`from_pretrained` raises `TypeError`). `info` adds `extra_inputs` and `input_schema`; `__call__` re-checks +`closed` once it holds the lock. + +--------------------------------------------------------------------------------------------------------------------- + +## 11. Server (C08, `ttaw.server`) + +`create_app(spec: ServerSpec, *, model_factory=None) -> FastAPI` implements BUNDLE_CONVENTIONS.md section 7: +`GET /` (routes), `GET /health` and `/v1/health` (always 200: `ok` / `starting` / `error`, plus device), +`GET /info` (model, task, io, autoware, weights, device, input limits, calibration presets, labels, variants, +runtime / compile params, warm-up and boot ms, source), `GET /v1/models` (stub), `POST /predict`. Errors: 400 +(`InputError`, bad params, body above `_MAX_BODY_MB` by Content-Length), 422 (schema: unknown fields are +refused), 503 (starting / failed boot), 500 (`inference failed: : `). The lifespan reads the environment +once (`config_from_env`), refuses a `TT_MESH_SHAPE` other than 1x1, builds the model through +`spec.model_cls.from_pretrained` (or `model_factory(cfg)`), and closes it on shutdown under the lock. A body holding a +NaN / infinity (strict JSON has none) is a 500 `inference failed: non-finite value at body.`. `/info` `input` +also lists `extra_inputs` and `input_schema`. + +`ServerSpec(model_name, env_prefix, model_cls=None, task="", default_weights="", owner="changh95", hardware=HARDWARE, +io="", autoware={}, source={}, calib_dir=None, default_variant=None, version="0.1.0", description="", +request_model=PredictRequest, decode_extra=None, info_extra=None)`. Model-specific request fields: subclass +`PredictRequest` (e.g. `rois: Optional[List[...]] = None`), add them to the call kwargs in +`decode_extra(request, kwargs, max_bytes)` and list them in the model's `EXTRA_INPUTS`. `app.state.ttaw` +(`ServerState`) holds `model`, `config`, `ready`, `error`, `lock`, `model_factory` (tests: assign a stub before +`TestClient(app)`) and `predict` (the route handler, for API == server checks). Also exported: +`parse_mesh_shape`, `config_from_env(spec, env=None)`, `default_model_factory(spec)`, `decode_request(req, spec, +max_bytes)`, the request models `PointsSpec`, `SweepSpec`, `ImageSpec`, `StreamSpec`, `ArraysSpec`, +`PredictRequest`. + +`ttaw.server.client` and `ttaw.server.smoke` are standard-library only and import nothing from ttaw, so a bundle's +`smoke_test.py` (run by `container_smoke.sh` with the host's `python3`, which has no numpy) loads them by path: + +```python +HERE = Path(__file__).resolve().parent # code//server +sys.path.insert(0, str(HERE.parent / "ttaw" / "server")) +import client as ttaw_client +import smoke as ttaw_smoke +health = ttaw_client.wait_ready(url, wait_s=600) +info, fails = ttaw_client.check_service(url, expect_dispatch="eth", expect_grid="12x10") # PLAN 0.3 item 6 +pinned = ttaw_smoke.pinned_config(f"{staged}/tt_kernel_manifest.json", profile) # serve.env + profile +fails += ttaw_smoke.check_pinned(info, pinned, "CENTERPOINT") # /info runs the pins +code, body = ttaw_client.post(url, ttaw_client.build_request(points=str(SAMPLE))) +if ref := ttaw_smoke.find_reference(SAMPLE, pinned["profile"], info.get("variant")): # stored CPU output + metrics, more = ttaw_smoke.compare_with_reference(body, ttaw_smoke.load_json(ref), gates={"min_recall": 0.95}) + fails += more +fails += [f] if (f := ttaw_client.check_bad_request(url)) else [] +print(ttaw_client.smoke_line("centerpoint-p150", f"n={body.get('num_detections')}", fails)) +``` + +Functions: `build_request(points=None, fields=None, images=(), calib=None, calib_preset=None, inputs=None, +params=None, stream_id=None, reset=False, output_format="json")`, `post(url, payload, timeout=120)`, +`get_json(url, timeout=10)`, `wait_ready(base, wait_s=0, poll_s=5)`, `check_service(base, *, expect_dispatch="eth", +expect_grid="12x10") -> (info, failures)`, `check_bad_request(base, payload=None)`, `smoke_line(model, summary, +failures)`, `b64file`, `main` (CLI: `--points/--image/--calib/--calib-preset/--inputs/--param/--out/--url`). + +`ttaw.server.smoke` functions: + +| name | meaning | +|---|---| +| `compare_with_reference(body, reference, gates=None) -> (metrics, failures)` | served `/predict` body vs the stored CPU-reference body of the same input, by the reference's keys: `detections` (greedy same-label matching in descending reference score; 3-D rows by BEV centre distance, 2-D rows by IoU; recall, precision, max score difference), `trajectory` (ADE / FDE over x, y), every encoded array (integer: fraction of equal elements; float: max abs difference, equal infinities agree, a NaN fails), `model` / `frame_id` equal. Undecodable input is a failure, never an exception | +| `DEFAULT_GATES` | `max_center_dist` 0.5 m, `min_iou` 0.5, `min_recall` 0.95, `min_precision` 0.95, `max_score_err` 0.05, `min_label_agreement` 0.99, `max_abs_err` None (report only), `max_ade` 0.5, `max_fde` 1.0; `gates=` overrides by name (unknown names raise) | +| `find_reference(sample, *keys)` | first existing `..reference.json` (keys: serve profile, model variant), else `.reference.json`, else None | +| `pinned_config(manifest, profile=None)` | `{"profile", "env", "weights"}` of a staged `tt_kernel_manifest.json`: `serve.env` with the profile's env on top (tt-model's merge), default profile when None | +| `check_pinned(info, pinned, prefix)` | `/info` agrees with the pinned `_DISPATCH`, `_NUM_CQS`, `_VARIANT` and the weights revision (absent pins are not checked) | +| `decode_array(spec) -> Array(shape, dtype, values)` | numpy-free decoding of `io.encode_array` (npz, npz_compressed, raw, list; C or Fortran order, either byte order) and `io.encode_png` (8-bit grey / RGB(A), every PNG filter) | +| `describe_metrics(metrics)`, `load_json(path)`, `ARRAY_FORMATS` | helpers | + +The reference body is the `to_dict()` of the fp32 CPU reference on the shipped sample, stored next to it as +`.reference.json` (per profile or variant when the output depends on it). Synthetic samples may give no +detections, so agreement with that reference, not a detection count, is their smoke gate (PLAN.md section 6.3). + +--------------------------------------------------------------------------------------------------------------------- + +## 12. Vendoring (C09, `common/tools/vendor.py`) + +`python common/tools/vendor.py [--pkg tt_] [--rev REV] [--allow-dirty] [--check] [--dry-run]`. + +- **What is vendored is a committed revision**: `ttaw/` as committed at `--rev` (default `HEAD`), read with `git + archive`, never the working tree of `common/` (other agents' uncommitted modules live there: YOLOX PORT_LOG Q7). + Uncommitted changes under `common/ttaw` (staged, unstaged, untracked) are listed in a WARNING and left out: + commit your change (`git add `, bump the version + CHANGELOG), then vendor. The revision is resolved + once, so a commit landing meanwhile never mixes into the recorded `source_commit`. +- `--allow-dirty` vendors the working tree instead, for a local experiment only: `source_dirty` is true when it had + uncommitted changes or its files differ from `ttaw/` of HEAD (.gitignore'd files included: `source_dirty: false` + always means "verified against `source_commit`"); `check_bundle.py` warns about such a copy and refuses it at + `--stage publish`. Outside a git checkout the working tree is vendored with `source_commit: null` (same + treatment). +- The destination must be a plain directory: one that is, or reaches through a symlink, `common/ttaw` (or an + ancestor of it) is refused before anything is written (mirroring HEAD there would delete other agents' untracked + files and revert their uncommitted changes). +- The copy mirrors that tree into `code//ttaw` (stale files removed; `__pycache__`, `*.pyc`, `*.bin`, `*.log` + never copied) and writes `VENDORED.json`: `version` (of the vendored `__init__.py`), `source_commit` (full sha), + `source_ref` (the `--rev` given), `source_tree` (`commit` | `working-tree`), `source_dirty`, `vendored_at`, + per-file sha256. `research/packaging/scripts/instantiate_bundle.py --out` vendors the same way (`--vendor-rev`, + `--vendor-allow-dirty`; an existing copy is kept unless `--force`, and always with `--only `). +- `--check` (exit 1 on any line): "modified in bundle" / "missing in bundle" / "extra in bundle" (the copy vs its + `VENDORED.json`); "not at recorded revision " (`VENDORED.json` is not `ttaw/` of `source_commit`; + "unverified:" when that commit is not in `common/`; skipped for a `source_dirty` copy); "outdated:" (`VENDORED.json` + vs `ttaw/` committed at `--rev`, default HEAD: re-vendor and re-run the gates). Uncommitted work in `common/ttaw` + never makes a bundle look outdated. `check_bundle.py` reports "outdated:" and "unverified:" as warnings (errors at + `--stage publish`), every other line as an error. + +Never edit the vendored copy: change `common/ttaw`, bump `__version__` + CHANGELOG, commit, re-vendor every consumer +and re-run their gates (PLAN.md section 5.1 step 5). Functions: `vendor(bundle, pkg=None, *, dry_run=False, rev=None, +allow_dirty=False)`, `check(bundle, pkg=None, *, rev=None)`, `load_source(rev=None, *, allow_dirty=False) -> Source`, +`rev_files(rev)`, `rev_hashes(rev)`, `rev_version(rev)`, `resolve_rev(rev)`, `dirty_paths()`, `tree_hashes(root)`, +`source_version()` (working tree), `git_state()`, `find_package(bundle, pkg)`; git calls never take the index lock +(`GIT_OPTIONAL_LOCKS=0`). + +--------------------------------------------------------------------------------------------------------------------- + +## 13. Measured facts and pitfalls (this p150b, tt-metal 44d6650 + ETH patch) + +Device results of the ttaw suites and probe P2 are recorded in `common/probes/p2-trace-runner.md`. In short: + +- ETH dispatch opens 12x10 with 1 and 2 CQs, WORKER 11x10, `auto` -> ETH (`tests/device/test_open_device.py`). +- In-trace `ttnn.copy` into persistent float32 / uint32 / bfloat16 tensors, ping-pong traces, RT-dev scalar params, + packed readback, 2CQ uploads (direct and staged), CQ1 readback and replay == eager are bit-exact. +- A ROW_MAJOR tensor is one page per row, and the RM `reshape` / `pad` / `concat` programs stage whole pages in L1: + `reshape_rm_program_factory.cpp` needs 2 x (destination page + 80 B) per kernel copy (two copies when the pages + divide each other) when the pages are not 16-byte aligned, out of ~1.43 MB free L1 per core + (`TT_FATAL ... RM reshape dest staging does not fit in L1: need at least 1497632 B dest + 512 B source, have + 1461248 B`, YOLOX's `[1, 1, 1, 187200]` fp32 row). Keep RM rows (last dim x element size) well below 0.5 MB; + `pack_outputs` does (section 3). +- A program-cache miss inside a capture raises with the op name and leaves the device usable. +- numpy uint32 arrays (including values >= 2**31) upload exactly; int64 arrays must not be passed to + `ttnn.from_torch` directly (they would go through bf16): use `tensors.to_host_tensor`. +- `numpy.asarray(host_buffer)` fails and `numpy.from_dlpack` is read-only; `torch.from_dlpack` is a writable alias + (`HostStaging`). +- `ttnn.matmul` with an explicit HiFi4 + fp32 config: max |error| 0.03 vs fp64 on a 64x512x128 product; LoFi 2.4. +- Runner cost (34-program toy graph, 4 MiB input): `replay` b2b equals a raw `execute_trace` (0.857 ms); streaming + `run()` per frame 1.07 ms (1CQ), 1.09 ms (direct 2CQ: CQ1 must wait for the previous replay before overwriting the + input), **0.92 ms with `stage_inputs=True`** (upload hidden behind the replay). Use staging when uploads are large + and frames are pipelined; it buys nothing for a single synchronous request. +- `ttnn.to_torch` of a host tensor copies, so `read()` results stay valid after later reads. +- Review of 0.2.0 (ttaw 0.3.0, `logs/ttaw/review_*`): `ttnn.reshape` of a ROW_MAJOR tensor returns a view on the + same buffer, and `ttnn.deallocate(view)` (default `force=True`) frees the base tensor's memory + (`review_force_dealloc_probe.log`); a program first enqueued after a capture is a "program_cache" buffer the + allocation tracker refuses before the next replay (`review_old_staged_tracking_probe.log`). Ping-pong states + written through `ctx.write_target` (`output_tensor=`), D16 bank switches between two streams, `reset_state` from + a bank, `write_input` followed by a CQ1 upload, and a 2CQ run after a partially failed capture are bit-exact on + the p150b in 1CQ and 2CQ; with `TT_METAL_TRACE_ALLOC_TRACKING=1` bank switches and the 2CQ staged path allocate + nothing after capture. +- Where the 13 specs' other needs live: fp32 row gathers are `ttnn.gather` (FLOAT32, TILE; bit-exact but ~1 us per + picked index), bf16 rows `ttnn.embedding` (3-5 us; probe P13, `probes/g1-dispatch-genericop-state.md`); top-k, + argmax, conv / pool, attention / grid_sample facts are in `probes/g2..g4-*.md`; the op wrappers C17-C23 and + kernels K1-K11 are added by the first port that needs them (PLAN.md 1.2-1.3). RT-dev values of any shape are + `add_param` (re-uploaded only when they change) or, when they change every frame (index tables), `add_input`; + shape buckets are variants sharing `add_output` buffers; trace segments around a host fallback are variants handed + off through states or a read + `run(inputs=...)`; serve profiles pin `_VARIANT` / `_NUM_CQS` / `_DISPATCH`, + checked by `server.smoke.check_pinned`; temporal state per stream is `StreamBanks` (section 3). +- Device tests: run only your own files. `common/tests/device/` also holds the probe agent's `test_probe_p*.py`, + some of which spawn device subprocesses and must not run inside another pytest process. + +--------------------------------------------------------------------------------------------------------------------- + +## 14. Image pre-processing (C14, `ttaw.image`) + +Bit-exact host emulations of the resize kernels the Autoware camera nodes deploy, driven by per-source-size lookup +tables computed once and cached (a camera keeps its size). numpy only. A standard resize in their place moves the +network input enough to fail the PCC gates (YOLOX: `cv2.resize` drops the det-output PCC to 0.94, +research/yolox/SPEC.md section 3), so each preset is tested against a scalar transliteration of the deployed code. + +```python +from .ttaw.image import yolox_letterbox, yolox_letterbox_geometry + +bgr = rgb[:, :, ::-1] # Autoware feeds BGR8 (cv_bridge toCvCopy BGR8) +x_u8, geom = yolox_letterbox(bgr) # (960, 960, 3) uint8 HWC, BGR, pad 114 +x_onnx = yolox_letterbox(bgr, layout="nchw")[0].astype("float32") # == the ONNX input `images` (1, 3, 960, 960) +geom.scale, geom.resized_hw, geom.mask_hw # float32 scale (decoder), (r_h, r_w), mask crop + +from .ttaw.image_linear import sceneseg_preprocess, sceneseg_resize, opencv_resize_nearest +u8 = sceneseg_resize(bgr) # (320, 640, 3) uint8: cv::resize INTER_LINEAR, exact +x = sceneseg_preprocess(bgr, channel_order="bgr") # == the SceneSeg ONNX input (1, 3, 320, 640) float32 +mask_src = opencv_resize_nearest(mask_320x640, bgr.shape[:2]) # the node's INTER_NEAREST back to the source size +``` + +| name | meaning | +|---|---| +| `yolox_letterbox(image, dst_hw=(960, 960), *, pad_value=114, layout="hwc", out=None)` | autoware_tensorrt_yolox `preprocess.cu:43-129` @ 9ceaccf: inverted half-magnitude "bilinear" weights, `fmaf` single roundings, float -> int truncation between the passes, `lroundf`, top-left letterbox (114), channel order kept -> `(uint8 HWC or (1, C, H, W), LetterboxGeometry)`. Needs a source of at least 2x2 | +| `yolox_letterbox_geometry(src_h, src_w, dst_h=960, dst_w=960)` -> `LetterboxGeometry` | `scale` (exact float32 value as a float; `scale_f32`), `resized_hw` = `(r_h, r_w)`, `mask_hw` (Autoware's mask crop, the same pair), `src_hw`, `dst_hw`, `pad_value`, `to_dict()` | +| `yolox_letterbox_lut(src_h, src_w, ...)` -> `YoloxLetterboxLUT` | the cached tables (`rows`, `row_w`, `cols`, `col_w`, `k`); `.apply(image, *, out=None, chunk_rows=96)` (any channel count) | +| `LUTCache(maxsize=8)` | the thread-safe LRU the presets use (`.get(key, make)`, `.hits`, `.misses`, `.clear()`) | +| `lroundf(x)`, `f32(x)` | C `lroundf` (half away from zero) and one float32 rounding, for presets and their tests | +| `bevdet_nearest_crop(image, *, channels="rgb", src_hw=(900, 1600), dst_hw=(256, 704), crop_hw=(140, 0), out=None)` | the `bevdet::Preprocess` plugin of autoware_tensorrt_bevdet (bevdet_vendor 0.2.1, research/bevdet/SPEC.md 3.2): nearest resize by r = (float)dst_w / src_w = 0.44f and crop (140, 0) of the 1600x900 image, `roundf(i / r + crop_h / r)` rows (318, 320, 323, ..., 898) and columns (0, 2, 5, ..., 1598) in float32 -> `(3, 256, 704)` uint8 **B, G, R** planes. `channels` is the input order (`"rgb"` from `ttaw.io.load_image`, `"bgr"` from OpenCV). The node's `cv::resize` of other image sizes to 1600x900 is the caller's (OpenCV) | +| `bevdet_nearest_lut(src_hw, dst_hw, crop_hw)` -> `NearestCropLUT` | the cached gather (`rows`, `cols`, `resize`); `.apply(image, *, channels, out)`, `.apply_planes(planes [..., C, H, W])` | +| `bevdet_normalize(crop, mean=BEVDET_MEAN, std=BEVDET_STD)` | `(x - mean[c]) / std[c]` in float32 on B, G, R planes (`BEVDET_MEAN` / `BEVDET_STD` are the "RGB" ImageNet numbers, applied to BGR planes as trained) | +| `bevformer_preprocess(images, *, mean=BEVFORMER_MEAN_BGR, std=BEVFORMER_STD, scale=0.8, pad_divisor=32, out=None, workers=1)` | autoware_tensorrt_bevformer's pipeline (research/bevformer/SPEC.md 3.1): N BGR uint8 images of one size (the node's 1600x900) -> normalise first (`(x - mean_c) / std_c` as OpenCV's `convertTo`: BGR means 103.53 / 116.28 / 123.675, std 1) -> `cv::resize` x0.8 INTER_LINEAR **on float** -> zero pad bottom / right to /32 -> `[N, 3, 736, 1280]` float32 B, G, R planes (the ONNX input `image` without its leading 1). `workers` threads over the cameras. The node's uint8 `cv::resize` of other sizes to 1600x900 is the caller's (OpenCV) | +| `bevformer_input_geometry(src_hw=(900, 1600), scale=0.8, pad_divisor=32)` | `{"src_hw", "resized_hw", "padded_hw"}`: `(int)(src * 0.8f)` in float32 and the /32 pad: (720, 1280) and (736, 1280) deployed (the network normalises its UV by the padded size) | +| `bevformer_normalize(image, mean, std)` | the normalisation alone, HWC float32 | +| `opencv_linear_lut(src_hw, dst_hw, *, strict=True)` -> `LinearResizeLUT`; `opencv_resize_linear_f32(image, dst_hw, *, strict=True)` | OpenCV's float INTER_LINEAR (`resize.cpp` coefficients `f = (float)((d + 0.5) * scale - 0.5)`, border clamps; each pass `fma(x1 - x0, w, x0)` in float32, horizontal first), cached tables (`rows0`, `rows1`, `wy`, `cols0`, `cols1`, `wx`); `.apply(image HWC)`, `.apply_planes(planes [..., H, W])` (strided block slices for periodic taps). `strict=True` refuses geometries not verified bit-exact (weights not multiples of 1/8: OpenCV computes other scales' coefficients differently) and exact 2x down-scales (OpenCV's INTER_AREA path) | +| `PRESETS` | name -> (function, description) of the implemented presets | +| `image_area.meteor_resize(image, *, out=None)` | METEOR (tier4/METEOR `hf/onnx_smoke_test.py:42-44`, research/meteor/SPEC.md 3): one uint8 frame (any channel order) -> 432x768 with OpenCV `INTER_AREA` (a copy when already 432x768). Down-scaling only (raises `ValueError` for any axis smaller than the target) | +| `image_area.opencv_resize_area_u8(image, dst_hw, *, out=None)`, `opencv_area_lut(src_hw, dst_hw)` -> `AreaResizeLUT` | OpenCV `cv::resize(INTER_AREA)` of uint8 HxW / HxWxC images, any down-scale: `resizeArea_` (`computeResizeAreaTab` float weights from double, horizontal then vertical float32 accumulation in table order, `cvRound`) and `resizeAreaFast_` for integer factors (float32 `s * (1.f / area)`, except the 2x2 `fast_mode` of 1-, 3- and 4-channel images: `(s + 2) >> 2`); cached tables (`fast`, `rows`, `row_w`, `cols`, `col_w`) | +| `image_area.scale_intrinsics(K, src_hw, dst_hw=(432, 768))` | K of the resized image: row 0 x dst_w / src_w, row 1 x dst_h / src_h (METEOR `extract_gt.py:128-130`; anisotropic resizes keep fx != fy), float64 | +| `image_linear.sceneseg_preprocess(image_bgr, *, channel_order="bgr")` | VisionPilot SceneSeg (`middleware_recipes/common/backends/onnx_runtime_backend.cpp:41-60` @ vision_pilot 04fa3e80; research/sceneseg/SPEC.md 3): one HxWx3 B, G, R uint8 frame -> the ONNX input `float32 [1, 3, 320, 640]`, bit-exact = `sceneseg_normalize(sceneseg_resize(image))`. `channel_order`: `"bgr"` (deployed: B, G, R planes, BGR-ordered ImageNet constants) or `"rgb"` (training order: R, G, B planes, RGB constants; a channel permutation of the bgr input) | +| `image_linear.sceneseg_resize(image_bgr, *, dst_hw=(320, 640), out=None)`, `sceneseg_normalize(resized_bgr, *, channel_order="bgr")` | the node's squash `cv::resize(img, Size(640, 320))` (INTER_LINEAR, aspect not kept) -> uint8 `(320, 640, 3)`, channel order kept (the TT device input); the normalisation as OpenCV computes it: `convertTo(CV_32F, 1/255)` (float32 product), `cv::subtract(Scalar)` in float32, `cv::divide(Scalar)` in double rounded to float32 (a float32 division differs by 1 ulp in ~27 % of the values), `cv::split` -> NCHW. `SCENESEG_INPUT_HW`, `SCENESEG_MEAN_RGB`, `SCENESEG_STD_RGB`, `SCENESEG_CHANNEL_ORDERS` | +| `image_linear.opencv_resize_linear_u8(image, dst_hw, *, out=None)`, `opencv_linear_u8_lut(src_hw, dst_hw)` -> `LinearResizeU8LUT` | OpenCV `cv::resize(INTER_LINEAR)` of uint8 HxW / HxWxC images, any scale: `resize()`'s float coefficients (`fx = (float)((dx + 0.5) * scale - 0.5)`, x-border fix only), `cvRound(w * 2048)` weights, the exact int32 horizontal pass and the uchar fixed-point vertical pass `(((b0 * (h0 >> 4)) >> 16) + ((b1 * (h1 >> 4)) >> 16) + 2) >> 2`; a copy for equal sizes and OpenCV's INTER_AREA fast path (`image_area`) for an exact 2x down-scale. Cached tables (`mode`, `cols0`, `cols1`, `a0`, `a1`, `rows`, `r0`, `r1`, `b0`, `b1`); `.apply(image, *, out=None)` | +| `image_linear.opencv_resize_nearest(image, dst_hw, *, out=None)`, `opencv_nearest_lut(src_hw, dst_hw)` -> `NearestResizeLUT` | OpenCV `cv::resize(INTER_NEAREST)` (`resizeNN`: `min(floor(x * (1.0 / inv_scale)), W - 1)` in double) of HxW / HxWxC images of any dtype (a gather): e.g. SceneSeg's 320x640 mask back to the source size (`run_model_node.cpp:117-188`) | +| `image_triangle.streampetr_preprocess(image, *, preset="autoware_main", channels="rgb", dst_hw=(480, 640), fma=False, out=None)` | autoware_camera_streampetr (universe main @ 9ceaccf, `lib/network/preprocess_kernel.cu:73-176` + `camera_data_store.cpp:287-316`; research/streampetr/SPEC.md 3.1): one uint8 `(H, W, 3)` frame (`channels` = its byte order) -> the float32 network input `(3, 480, 640)`: `resize = max(480 / H, 640 / W)` (float32), the virtual resized image `((int)(H * resize), (int)(W * resize))`, top rows cropped (bottom kept) and the width centred, a PIL-style triangle filter with adaptive support (`centre = (r + 0.5) * scale - 0.5`, taps `ceilf(centre - support) .. floorf(centre + support)`, `w = max(0, 1 - |d| / support)` per axis, `w = wx * wy`), accumulated **y outer, x inner** in float32, divided by the weight sum, then `(v - mean[c]) / std[c]`, planar. `preset` (`STREAMPETR_PRESETS`): `autoware_main` (RGB planes, RGB stats; PLAN D7 default), `autoware_0.52` (an rgb8 camera on 0.52.1: RGB planes, BGR-ordered stats), `awml_training` (BGR planes, BGR stats). `fma=True` models nvcc's default `--fmad=true` contraction (`fmaf` centre, channel and weight sums); `False` (default) rounds every C operation once, as the SPEC's port and the research goldens | +| `image_triangle.streampetr_preprocess_batch(images, *, preset, channels, dst_hw, fma, workers=1, out=None)` | the cameras of one frame -> `(N, 3, 480, 640)` float32 (each camera its own size); `workers` threads over the cameras | +| `image_triangle.autoware_resize_geometry(src_h, src_w, dst_h=480, dst_w=640)` -> `TriangleGeometry`, `triangle_resize_lut(src_hw, dst_hw=(480, 640), *, geometry=None, fma=False)` -> `TriangleResizeLUT` | `calculate_image_processing_params` in float32 (`src_hw`, `resized_hw`, `roi_hw`, `roi_start` (y, x), `resize`, `to_dict()`); the cached per-size tap tables (`rows`, `row_w`, `cols`, `col_w`; zero-weight padding) with `.apply(image u8 HxWxC) -> (C, roi_h, roi_w)` float32 weighted means (before the normalisation; any channel count). `geometry=` serves other nodes of the kernel family (BEVFusion's camera branch: verify its kernel first) | +| `image_triangle.fma_f32(a, b, c)` | `fmaf` on float32 arrays: one rounding, exact (TwoSum-corrected float64; a float64 sum landing on a float32 tie is broken towards the exact value) | + +Facts: 0 mismatches against the scalar kernel on 12 source sizes and on the research golden input of the Autoware +test image; 40-170 ms per frame on the shared host (1080p about 130 ms), a few ms per new size for the tables. The +BEVDet gather equals the research golden network input of the nuScenes key-frame `sample0` bit for bit +(`tests/host/test_image_bevdet_host.py`). The BEVFormer pipeline equals OpenCV 4.8.1 and 4.11.0 bit for bit on +arbitrary float images for every x0.8 down-scale (the textbook two-product interpolation differs in ~10 % of the +samples), the research reference's OpenCV pipeline on random uint8 images, and the research golden `image` of the +nuScenes key-frame `sample0` (`tests/host/test_image_bevformer_host.py`, which also holds a scalar exact-rational +oracle); 0.5 s per 6 x 1600x900 frame single-threaded on the shared host, 0.15 s with `workers=4` (OpenCV itself: +0.16 s). The device version (K9, uint8 upload + on-device resample) is an optimization item. Presets still to add +(their ports): BEVFusion triangle resize with truncation (PLAN.md C14; `ttaw.image_triangle` holds the same kernel +family). The METEOR `INTER_AREA` preset (`ttaw.image_area`) equals `cv2.resize` of OpenCV 4.8.1 and 4.11.0 bit +for bit at every METEOR source size tested and a scalar transliteration of `resize.cpp` on small geometries +(`tests/host/test_image_area_host.py`); about 0.1-0.15 s per 1920x1080 frame, 0.4 s at 2880x1860, numpy single thread. +The SceneSeg preset (`ttaw.image_linear`, 0.16.0) equals `cv2.resize` INTER_LINEAR / INTER_NEAREST and OpenCV's +`subtract` / `divide` scalar arithmetic of OpenCV 4.8.1 and 4.11.0 bit for bit on 23 fixed and 40 random geometries +(down / up, odd sizes, 1-4 channels, the exact-2x and copy shortcuts), a scalar transliteration of `resize.cpp`, the +23 research device inputs of the SceneSeg public-data set (`input_u8_bgr_640x320.png`) and, within one ulp, the SPEC +reference's float pre-processing (`tests/host/test_image_sceneseg_host.py`); 25-35 ms per 640x320 squash (414x727 to +1080p) and about 8 ms for the normalisation on the shared host, numpy single thread (OpenCV: 2-3 ms). +The StreamPETR preset (`ttaw.image_triangle`, 0.17.0) equals a scalar transliteration of the CUDA kernel bit for bit +in both contraction models (4 small geometries: down / up-scaling, crops, identity; 300 sampled pixels + the corners of +a 1920x1080 -> 480x640 frame), a scalar transliteration of `calculate_image_processing_params` on 15 source sizes, the +SPEC's numpy port (`research/streampetr/scripts/sp_common.py`) and the sha256 of the float32 network inputs of the +research goldens of the PandaSet ship sample (`tests/host/test_image_triangle_host.py`). The two contraction models +differ in ~43 % of the inputs by at most ~3e-5 (normalised units; the centre's last ulp moves the tap weights), far +below the device's bf16 input rounding. About 0.25-0.4 s per 1920x1080 camera on the shared host (numpy, one +thread), ~1.1 s per five-camera frame with `workers=4`. + +--------------------------------------------------------------------------------------------------------------------- + +## 15. LiDAR host pipeline (C10 `ttaw.geometry`, C11 `ttaw.pointcloud`, C12 `ttaw.voxelize`, C15 `ttaw.nms`, C16 `ttaw.decode`) + +Host pre- and post-processing of the Autoware LiDAR detectors, built by the CenterPoint port (research/centerpoint/ +SPEC.md sections 3 and 5) for CP, PP, TF and BF. numpy only. Each reproduces the deployed C++ / CUDA, including its +float32 arithmetic where that decides a cell or a threshold; the non-deterministic parts of Autoware (time-seeded +point shuffle, atomic slot / pillar order, unstable sorts) become fixed, documented policies (PLAN.md D1). + +```python +from .ttaw.pointcloud import StreamDensifiers, densify_sweeps, nonzero_rows +from .ttaw.voxelize import PillarGridSpec, assign_pillars, decorate_pillar_features, canvas_gather_index +from .ttaw.decode import CenterHeadDecodeConfig, decode_centerhead, sort_by_score, to_detected_objects +from .ttaw.nms import circle_nms, iou_bev_nms, ClassRemapper + +spec = PillarGridSpec((-76.8, -76.8, -4.0), (76.8, 76.8, 6.0), (0.32, 0.32, 10.0), 32, 40000, order="flipped_x") +cache = StreamDensifiers(num_past_frames=1).get("front") # Autoware's PointCloudDensification, per stream +cache.enqueue(xyz, stamp_s, T_world_from_ego) # False: no pose -> frame skipped, not cached +pts, info = cache.sweep_points() # (N, 4) x, y, z, time_lag; current sweep first +pil = assign_pillars(pts, spec, shuffle_seed=0) # first 32 per cell, ids in flipped-x order +feats = decorate_pillar_features(pil, spec, encoder_in_feature_size=9) # (40000, 32, 9) generateFeatures_kernel +index = canvas_gather_index(pil.coords, pil.num_pillars, spec, sentinel=40000) # NHWC canvas = table[index] +boxes = sort_by_score(decode_centerhead(heads, cfg)) # cfg = CenterHeadDecodeConfig.create(...) +keep = circle_nms(boxes.x, boxes.y, 0.5) +objs = to_detected_objects(boxes.take(keep), cfg.class_names) # ObjectClassification labels, yaw_ros +objs = objs.take(iou_bev_nms(objs.x, objs.y, objs.length, objs.width, objs.yaw, objs.label)) +objs.label = ClassRemapper.from_params(remapper_yaml_params).apply(objs.label, objs.length, objs.width) +``` + +| module / name | meaning | +|---|---| +| `geometry.compose`, `invert_rigid`, `transform_points`, `as_transform`, `transform_from_xyz_rpy`, `rotation_from_rpy` | float64 rigid transforms (`T_a_from_b`); `as_transform` accepts every `io.parse_transform` spelling | +| `geometry.invert_affine_f32`, `compose_f32`, `transform_points_f32` | Autoware's float32 path: `Eigen::Affine3f` inverse (cofactors, column-0 determinant) and product, and `generateSweepPoints_kernel` (`((m0 x + m1 y) + m2 z) + m3`, no FMA) | +| `geometry.mmdet_yaw_to_ros`, `ros_yaw_to_mmdet`, `quaternion_wxyz_from_yaw`, `yaw_from_quaternion_wxyz`, `yaw_from_rotation`, `wrap_angle` | yaw conventions (`yaw_ros = -yaw_net - pi/2`, float result as `ros_utils.cpp:55`) | +| `pointcloud.SweepDensifier(num_past_frames=1, cloud_capacity=2_000_000)` | one stream's cache: `.enqueue(xyz, stamp_s, T_world_from_sensor=None, *, intensity=None) -> bool` (pose required when `num_past_frames > 0`; a missing pose leaves the cache unchanged), `.sweep_points(*, point_feature_size=4\|5) -> (points, DensifyInfo)` (float32 `world2current @ past2world` per sweep, `time_lag = float32(t_now - t_sweep)`, capacity drops a sweep and every older one), `.reset()`, `.stamps`, `.describe()` | +| `pointcloud.StreamDensifiers(..., max_streams=16)` | per-`stream.id` caches with LRU eviction: `.get(id, reset=False)`, `.forget(id)`, `.streams`, `.describe()` | +| `pointcloud.densify_sweeps(current_xyz, [(xyz, time_lag_s, T_current_from_sweep)], ...)` | the stateless client-side variant -> `(points, DensifyInfo)` | +| `pointcloud.finite_rows`, `nonzero_rows`, `range_mask`, `seeded_permutation(n, seed)` | hygiene masks (`nonzero_rows` = `|x|+|y|+|z| > 0`, the research rule for organized-cloud fillers; `range_mask` half-open, NaN fails) and `default_rng(seed).permutation(n)` | +| `voxelize.PillarGridSpec(range_min, range_max, voxel_size, max_points_per_pillar=32, max_pillars=40000, order="flipped_x"\|"raster")` | grid sizes in float32 as `centerpoint_config.hpp` (`grid_x`, `grid_y`, `num_cells`) | +| `voxelize.assign_pillars(points, spec, *, shuffle_seed=None) -> PillarSet` | deterministic pillars: optional seeded permutation, half-open range, float32 `floor((v - min) / voxel)` clamped, first K per cell in input order, ids in ascending cell order capped at `max_pillars`. `PillarSet`: `points (P, K, F)`, `num_points`, `coords (z, y, x) = (0, iy, ix)`, `num_pillars`, `num_pillars_total`, `overflow`, `stats()` | +| `voxelize.decorate_pillar_features(pillars, spec, *, encoder_in_feature_size=9\|10\|11)` | `generateFeatures_kernel`: raw columns, offsets to the slot-ordered float32 mean, offsets to the pillar centre `voxel/2 + coord*voxel + min`; padded slots 0 | +| `voxelize.scatter_canvas(features, coords, n, spec)`, `canvas_gather_index(coords, n, spec, *, sentinel)` | `scatterFeatures_kernel` (C, H, W) and its gather form for the device (C19): cell `iy * grid_x + ix` -> pillar row or the zero sentinel row | +| `decode.CenterHeadDecodeConfig.create(class_names, voxel_size_xy, range_min_xy, downsample_factor, distance_bin_upper_limits, score_thresholds, yaw_norm_thresholds, has_variance=False, has_twist=False)` | Autoware's coercions (thresholds outside [0, 1) -> 0, ascending bins, one yaw threshold per class); thresholds `(bins, classes)`; `.with_score_threshold(v)` | +| `decode.decode_centerhead(heads, cfg) -> DecodedBoxes`, `sort_by_score` | `generateBoxes3D_kernel` in float32 (first-max label, no +0.5 offset, bins, `score < thr` drops, yaw-norm gate, dims (w, l, h), `atan2`), rows in cell order; stable descending sort (ties by cell). No max-pool, no top-K | +| `decode.head_values_at(heads, cells) -> {name: (C, K)}`, `decode_cells(values, cells, grid_w, cfg) -> DecodedCells` | the same decoder at given cells, dropping none (agreement metrics: device vs fp32 reference at the same cells). `DecodedCells`: the `DecodedBoxes` fields (bit-identical to `decode_centerhead`'s row for every cell it keeps) plus `yaw_norm`, `distance_bin`, `score_threshold`, `yaw_norm_threshold`, `passes_score`, `passes_yaw_norm`, `.keep`, `.take`, `.to_boxes()`; `head_values_at` stores the maps at a cell set (compact goldens) | +| `decode.to_detected_objects(boxes, class_names, *, has_twist=False) -> DetectedObjects` | `box3DToDetectedObject`: ObjectClassification labels (`AUTOWARE_LABELS`, `LABEL_IDS`, `semantic_label`), `yaw_ros`, (length, width, height), `orientation_availability` SIGN_UNKNOWN for car-like labels, object-frame twist; `.take`, `.boxes_xyzlwh_yaw()` (the `outputs.Detections3D` layout), `.to_records()` | +| `nms.circle_nms(x, y, dist)` | `circleNMS` on score-sorted boxes: float32 `dx^2 + dy^2 < dist^2` (strict), greedy, class-agnostic | +| `nms.iou_bev_nms(x, y, length, width, yaw, labels, *, search_distance_2d=10.0, iou_threshold=0.1, scores=None, sort=False)` | `perception_utils::IouBevNms::apply`: every earlier object (kept or not) suppresses, pedestrian-vs-other pairs skipped, `<=` search gate, break at `iou > thr`, keep iff `max_iou <= thr`; exact rotated-rectangle IoU (`iou_bev`, `clip_convex`, `polygon_area`, `bev_box_corners`) with the 1e-6 / 0.01 area guards | +| `nms.ClassRemapper.from_params(yaml_params)` / `.from_lists(allow, min, max)` | `DetectionClassRemapper`: `.apply(labels, length, width)` with `bev_area = float(l * w)`, first allowed destination in label order | + +Facts (CenterPoint port, research/centerpoint): voxel tensors bit-identical to the research reference (input order +and seed 0, including a 41,918-pillar overflow frame); decode + NMS + remapper give the same objects as two +independent research implementations on 16 head-map goldens; about 0.3 s voxelization and 30-120 ms +post-processing per 200k-point frame on the shared host (numpy). Host tests: +`tests/host/test_geometry_pointcloud_host.py`, `test_voxelize_host.py`, `test_decode_nms_host.py`. Still to add (their +ports): PointPainting 12-feature decoration and raster order use, TransFusion / BEVFusion decoders, OpenPCDet and +METEOR NMS variants (PLAN.md C12, C15, C16). + +--------------------------------------------------------------------------------------------------------------------- + +## 16. CNN ops: conv builders (C17 `ttaw.ops.conv`), up-sampling and interpolation (C18 `ttaw.ops.upsample`) + +Built by the YOLOX port (PLAN.md C17 / C18; probes P5, P14). A feature map is a `FeatureMap(tensor, batch, height, +width, channels)`: the device tensor holds N*H*W rows of C channels (ttnn's flattened `[1, 1, N*H*W, C]`, TILE or +ROW_MAJOR), plus the spatial size ttnn's layout no longer carries. Every builder prepares its device weights on its +first (eager) call and reuses them, so call each layer once before capturing (the `TraceRunner` warm-up does): a +host weight write inside a capture fails ("Writes are not supported during trace capture"). + +```python +from .ttaw.ops.conv import Conv2d, KSplitConv, ConvTranspose2d, FeatureMap, concat_channels, residual_add +from .ttaw.ops.upsample import upsample_nearest, Resize2d, interp_matrix + +conv = Conv2d(w_oihw, b, stride=2, activation="relu6") # padding "same" (k // 2); HiFi4 + fp32 + L1 acc +x = FeatureMap(ctx["image_bf16"], 1, 960, 960, 3) # or fmap_from_numpy(nchw, device) (under devrun) +y = conv(x) # FeatureMap [1, 1, 480*480, 32], DRAM, TILE +y = residual_add(conv2(y), y, "relu6") # RELU / RELU6 fused into ttnn.add (P5) +z = concat_channels([upsample_nearest(lateral, 2), d4]) # nearest x2: bit-exact; concat along C +head = Conv2d(w, b, output_dtype="float32") # fp32 logits for thresholds +ks = KSplitConv(w_full, b, parts=(128, 128, 128), activation="relu") # conv(concat) without the concat (P14) +up = ConvTranspose2d(w_iokk, b, stride=4, activation="relu") # k = 2: conv_transpose2d; k >= 3: linear + d2s (P5) +rs = Resize2d((16, 44), (64, 176), channels=256, mode="linear", align_corners=True) # FPN_LSS-style bilinear +``` + +| name | meaning | +|---|---| +| `Conv2d(weight, bias=None, *, stride=1, padding="same", dilation=1, groups=1, activation=None, precision=CONV_PRECISION, output_dtype="bfloat16", output_layout="tile", slicing="auto", output_memory_config="dram", conv_config=None, weight_terms=1, name="conv")` | `ttnn.conv2d` with weights prepared once per input spec. `__call__(fmap)` (or a raw tensor + `batch=`, `height=`, `width=`) -> `FeatureMap`. `slicing="auto"`: a DRAM input runs ttnn's DRAM-sliced path with automatic slice counts (P14: traceable; explicit counts are often rejected) and writes DRAM interleaved; an L1 input runs the L1 path; `"l1"` = `Conv2dL1FullSliceConfig`; `("height"\|"width", n)` explicit (diagnostics). 1x1 stride-1 convs are matmuls on the L1 path; `output_memory_config` (`"dram"` default, `"l1"`, None = the op's sharded output) places their output. `conv_config`: extra `ttnn.Conv2dConfig` fields (optimization knobs: `act_block_h_override`, `shard_layout`, double buffers, ...). `is_matmul`, `out_hw(h, w)`, `takes_l1_path(t)`, `prepared_specs`, `release()`, `describe()` | +| `weight_terms=2` | the weight and the bias as two bf16 terms (`hi = bf16(x)`, `lo = bf16(x - hi)`: ~16 significant bits; `host_terms()`), run as two convs into fp32 outputs, summed in fp32 with the activation fused into the add, cast to `output_dtype` (TILE outputs only): ~fp32 weights and bias for 2x the MACs and 3 more programs. **bf16 rounding of weights and biases, not of activations, dominates a deep CNN's error** (a per-channel bias error is the same at every pixel): YOLOX's mask agreement on PandaSet side cameras is 97.5 % with bf16 weights and 99.3 % with two terms (CPU emulation; the device matches it). The device's float32 weight path (`precision=":w=float32"`) is no substitute: 1.5x less error than bf16 vs 3.5x (fp32 output) for two terms; with a bf16 output two terms land within 1.05x of the output-rounding floor (`logs/yolox/m3_weight_precision_probe.log`, `m3_c17_weight_terms_device_r2.log`) | +| `CONV_PRECISION` | `"HiFi4+fp32+l1acc"`, the default of every builder. **Without packer L1 accumulation a conv whose inner dim spans several blocks keeps its partial sums in the output dtype (bf16) between blocks** (`conv2d_op_program_factory_common.cpp:175-178`): YOLOX 3x3 256 -> 256 PCC 0.99998 / max abs 0.25 vs 0.9999993 / 0.025 with it, at the same speed (`logs/ttaw/c17_c18_device_results*.json`) | +| `normalize_activation`, `unary_with_param`, `apply_activation`, `FUSED_ACTIVATIONS`, `BINARY_FUSED_ACTIVATIONS` | fused conv activations: relu, relu6, silu, gelu (exact), sigmoid; binary fused: relu, relu6. **HARDSWISH is refused** (fused, it is silently skipped: P5); apply `ttnn.hardswish` as its own op | +| `KSplitConv(weight, bias, parts, *, activation=None, output_dtype="bfloat16", accumulate_dtype="bfloat16", **conv_kwargs)` | `conv(concat(x_1..x_n))` as `sum_i conv_i(x_i)` (bias on the first part, activation fused into the last add or after it); `__call__([fmaps])`. `accumulate_dtype="float32"` keeps partials fp32. `split_k_weights(w, parts)` is the host split | +| `ConvTranspose2d(weight [Cin, Cout, k, k], bias=None, *, stride=k, activation=None, precision=CONV_PRECISION, output_dtype="bfloat16", method="auto", output_layout="tile", memory_config="dram")` | kernel == stride, no padding. `auto`: k = 2 -> `ttnn.conv_transpose2d`, k >= 3 -> `ttnn.linear` (bias + activation fused) + depth-to-space (RM reshape / permute / reshape); `linear_weights()` gives the (i, j, c)-ordered host matrix | +| `merge_sibling_convs(weights, biases) -> (w, b, sizes)`, `split_channels(fmap, sizes)` | one conv for sibling convs reading the same input (exact), split by `ttnn.slice` on C | +| `concat_channels(fmaps, *, memory_config="dram")`, `residual_add(a, b, activation=None)` | glue on maps of one spatial size | +| `FeatureMap` (`rows`, `hw`, `with_tensor(t, channels=None)`, `deallocate()`), `fmap_from_numpy(nchw, device, dtype, layout, memory_config)`, `fmap_to_numpy(fmap)`, `conv_padding`, `conv_out_hw`, `is_dram` | helpers (TILE uploads touch the device: run under `bin/devrun`) | +| `upsample_nearest(fmap, scale=2, *, output_layout="tile", memory_config="dram")` | integer-factor nearest (floor): TILE -> RM -> `[N, H, W, C]` -> `ttnn.upsample` -> `[1, 1, N*sH*H*sW*W, C]` -> TILE. Bit-exact (ONNX Resize nearest / asymmetric / floor) | +| `interp_matrix(n_in, n_out, *, mode="linear"\|"nearest", align_corners=False, scale=None)` -> `[n_out, n_in]` float64; `resize_matrices(in_hw, out_hw, ...)` | 1-D interpolation matrices equal to `F.interpolate` (torch's half-pixel rule clamped at 0, `align_corners`, the `scale_factor` rule); host tests compare them with torch at 1e-12 | +| `Resize2d(in_hw, out_hw, *, channels, batch=1, mode="linear", align_corners=False, scale=None, dtype="float32", output_dtype="bfloat16", precision="accurate", output_layout="tile", tail="auto")` | separable resize on the device for any sizes: W pass `[N*H, C, W] @ A_w^T` (transposes around one matmul), H pass `kron(I_N, A_h) @ [N*H, W'*C]`; `tail` (0.23.1): `tile` reshapes the H-pass result in TILE layout, `rm` via ROW_MAJOR (small DRAM pages: deadlocks Blackhole under ETH dispatch, SYS-1419), `auto` = `tile` for destination pages < 4 KB unless the tt-metal tree has the reshape patch (`ttaw.device.reshape_patch_present`, 0.23.2: then `rm`, the patched single-kernel path) (env `TTAW_RESIZE2D_TAIL`); `w_pass` (0.23.5 / 0.24.1; env `TTAW_RESIZE2D_WPASS`): `batched` (default) / `flat` (one 2-D matmul where C % 32 == 0) / `grid` (`flat` where C % 32 == 0, else the batched matmul with a fused-batch 1-D program config over the device grid, `wpass_grid_config`; bit-identical); fp32 operands by default (bf16 cannot hold weights like 511/1023; a device fp32 matmul is TF32-like, P12). `reference(nchw)` is its host float64 twin. `ttnn.upsample`'s own bilinear is half-pixel only (integer scales, sharded bf16 input) | + +Device results (`common/tests/device/test_conv_upsample_device.py`, every case eager x2, captured with cache misses +forbidden, replayed on a new input, and equal to an eager run after the capture bit for bit; log +`logs/yolox/m1_c17_c18_device_r1.log` / `_r2_l1acc.log`, results `logs/ttaw/c17_c18_device_results*.json`): all 54 +distinct conv shapes of YOLOX seg16 (1x1 to 9x9, stride 1 / 2, 960^2 down to 30^2, fused RELU6, fp32 head preds) +PCC >= 0.9999 (>= 0.9999992 for kxk with `CONV_PRECISION`); K-split 7 x 64 -> 128 0.99999; ConvTranspose k = 2 / 4 +0.99999; the 7 YOLOX nearest x2 shapes bit-exact (0.03-3.6 ms: the RM round trip dominates at 16 x 480^2); `Resize2d` +align_corners True / False, integer and non-integer, PCC >= 0.9999998. Host tests: `tests/host/test_conv_upsample_host.py` +(54) on the fake ttnn plus `tests/host/fake_ttnn_cnn.py` (conv2d / conv_transpose2d / upsample / matmul / argmax / +where / ... for CNN graph tests; `install(fake)` returns its undo). + +--------------------------------------------------------------------------------------------------------------------- + +## 17. Attention (C20, `ttaw.ops.attention`) + +Built by the Diffusion Planner port (PLAN.md C20; probe P7). `ttnn.transformer.scaled_dot_product_attention` has +four traps; `sdpa` is the only way the ports call it: + +1. `is_causal` defaults to True: with Sq == Sk it silently runs causal attention, with Sq != Sk it is rejected. + `sdpa` always passes `is_causal=False`. +2. The default `scale` is `1/sqrt(padded head dim)` (wrong after a 16 -> 32 head padding). `scale=` is required. +3. The default 32/32 chunks are 2.5-7x slower and inaccurate over >= 32k keys. `sdpa` passes a program config from + `chunk_config(sq, sk)` (the P7 table plus Sk-range rules) and refuses `program_config=None` once Sk >= 1,000. +4. **With a user mask the op masks the padded keys only at tile granularity**: key tiles past `ceil(Sk/32)` get + `-inf`, but the last partial tile is read from the mask, whose tile padding is 0 after a host tilize + (`sdpa/device/kernels/dataflow/reader_interleaved.cpp`, "Mask read"). Up to 31 padded keys then join the + softmax (score `q . k_pad`, value `v_pad`): rel-L2 0.18 instead of 0.025 at 321 x 321 with 89 valid keys, and + 0.06 for P7's masked 564 x 564 case. `sdpa` refuses a mask with `Sk % 32 != 0`: run masked attention on + `aligned_keys(n)` keys (the extra keys masked with `-inf` in the mask; free, the tiles are padded anyway). + Without a mask an unaligned Sk is exact (the op generates an element-wise padding mask). + +```python +from .ttaw.ops import attention as A + +q, k, v = A.split_qkv(qkv, 8) # [1, 1, S, 3*H*D] -> 3 x [1, H, S, D] (one program) +q, k, v = A.split_q_kv(q_proj, kv_proj, 8) # Q from LN(x), K|V from x, same S +qh = A.split_heads(q_cross, 8) # Q-only (cross-attention; K / V hoisted elsewhere) +mask = A.expand_key_bias(ctx["key_row"], 576) # [1,1,1,Sk] bias row (persistent input) -> [1,1,Sq,Sk] DRAM +o = A.sdpa(q, k, v, scale=1 / 32 ** 0.5, attn_mask=mask, concat_heads=True) # [1, 1, Sq, H*D] +runner.run("plan", inputs={"key_row": A.key_bias_row(np.r_[valid, np.zeros(12, bool)])}) # 564 real + 12 masked +wq, bq = A.pad_head_columns(w_q, b_q, 8, 16) # head dim 16 -> 32 in the weights (exact, free) +wo = A.pad_head_rows(w_out, 8, 16) +``` + +| name | meaning | +|---|---| +| `sdpa(q, k, v, *, scale, attn_mask=None, program_config="auto", compute_kernel_config=None, fp32_acc=False, concat_heads=False, memory_config=None)` | `[B, H, Sq, D]` x `[B, Hkv, Sk, D]` (bf16 / bfp8 / bfp4 TILE interleaved, D % 32 == 0) -> `[B, H, Sq, D]`, or `[B, 1, Sq, H*D]` with `concat_heads=True` (the op's `output_concat_heads`, no extra program). Mask: additive bf16 TILE in DRAM, `[1\|B, 1\|H, Sq, Sk]`, Sk tile-aligned; `-inf` is safe | +| `chunk_config(sq, sk) -> (q_chunk, k_chunk)`, `CHUNK_TABLE` | exact measured shapes (evidence string per entry), else Sk >= 16,384 q64 k1024; >= 4,096 q64 k512; >= 1,000 q64 k128; shorter q64 k64 (32 when the sequence fits one tile) | +| `sdpa_program_config(device, sq, sk, *, q_chunk=None, k_chunk=None, exp_approx_mode=None)`, `sdpa_compute_config(*, fp32_acc=False, fidelity="HiFi2", approx=True)` | `SDPAProgramConfig` over the grid read from the device; the explicit compute config equal to the op default (P7: HiFi4 / exact exp do not help; `fp32_acc` halves the max error at ~1.4x the time) | +| `split_heads(x, num_heads)`, `split_qkv(qkv, num_heads, *, num_kv_heads=None)`, `split_q_kv(q, kv, num_heads, *, num_kv_heads=None)`, `merge_heads(x)` | `[B, 1, S, H*D]` <-> `[B, H, S, D]` through `ttnn.experimental.nlp_create_qkv_heads` / `nlp_concat_heads` (one program each, bit-exact moves, the logical S kept). `split_q_kv` needs the same S for Q and K / V; cross-attention splits Q and K / V separately | +| `key_bias_row(valid) -> [1, 1, 1, Sk]`, `key_bias(valid, sq) -> [1, 1, Sq, Sk]`, `expand_key_bias(row, sq)`, `aligned_keys(n)` | host masks (0 / `-inf`, float32; upload bf16 TILE) and the traced expansion of a persistent bias row (`ttnn.repeat`, DRAM; one program per plan, not per call) | +| `padded_head_dim(d)`, `pad_head_dim(x)`, `pad_head_columns(w, b, H, D)`, `pad_head_rows(w, H, D)` | head dim padding to a multiple of 32 in the projection weights (exact: the padded output columns are 0, P7) | +| `attention_reference(q, k, v, *, scale, bias=None)`, `attention_matmul(q, k, v, *, scale, attn_mask=None, compute_kernel_config=None)` | float64 numpy oracle; small-MHA fallback with two matmuls + softmax for what SDPA rejects (e.g. fp32 Q / K / V; tile-aligned Sk) | + +Device results (`common/tests/device/test_attention_device.py`, 27 cases through `TraceRunner`: eager x2 +bit-identical, strict capture, replay on a new input set equal to an eager run bit for bit; set A nearly uniform +attention, set B peaked; gates frozen in `test_attention_device.gates.json`; `logs/diffusion-planner/c20_device_r2.log`, +results `logs/ttaw/attention_results.json`): PCC vs float64 0.99966-0.99983 at the DP shapes (576 x 576 and 352 x 352 +masked, 352 / 321 x 564), TF self 500 x 500 head dim 16 -> 32, SP self 900 x 1,668 and BF cross 500 x 32,400 +(q64 k1024, 0.46 ms); rel-L2 0.024-0.025 everywhere; split / merge / mask expansion bit-exact; the fp32 matmul +fallback PCC 0.999998. Trace ms per call: DP fusion 576 x 576 masked 0.061-0.092, DiT self 352 x 352 masked 0.063, +DiT cross 352 x 564 0.033. A canary (`test_raw_op_mask_padding_leak`) keeps the trap-4 evidence (raw op, 321 keys: +rel-L2 0.183); when tt-metal masks partial tiles it fails and the refusal can be relaxed. Watcher bring-up of the +smallest shape (`TT_METAL_WATCHER=2`) clean: `logs/diffusion-planner/c20_watcher_smoke.log`. Host tests: +`tests/host/test_attention_host.py` (27) with `tests/host/fake_ttnn_attention.py` (an SDPA fake that keeps the op's +defaults, so a caller forgetting `is_causal=False` / `scale` fails; head ops, repeat, matmul, softmax). + +--------------------------------------------------------------------------------------------------------------------- + +## 18. LiDAR device modules: gather-form scatter (C19 `ttaw.ops.gather`), SECOND + SECONDFPN (C24 `ttaw.models.second`), CenterHead (C25 `ttaw.models.centerhead`) + +Built by the CenterPoint port (PLAN.md C19, C24, C25; probes P4, P5, P14) on the C17 builders of section 16, for +CP, PP, TF and BF. Every module is built from BN-folded host (numpy) weights, prepares its device weights on its first +(eager) call, keeps every output in DRAM (interleaved TILE; L1 residency is optimization work) and traces. + +```python +from .ttaw.ops.gather import check_index, scatter_rows, gather_rows, scatter_rows_numpy +from .ttaw.models.second import ConvSpec, Second, SecondFPN, RowLinear, free_maps +from .ttaw.models.centerhead import CenterHead, merge_heads +from .ttaw.ops.conv import FeatureMap + +index = check_index(prep.canvas_index, num_rows=prep.num_pillars, sentinel=40000) # host, [1, H*W] uint32 +backbone = Second([[ConvSpec(w, b, stride=s) for w, b, s in block] for block in blocks]) # 3x3 + ReLU +neck = SecondFPN([ConvSpec(w0, b0), ConvSpec(w1, b1, stride=2, kind="conv_transpose"), + ConvSpec(w2, b2, stride=4, kind="conv_transpose")]) # 1x1, k2 ConvT, k4 ConvT +head = CenterHead(shared_spec, [128, 128, 128], [(name, hidden_spec, final_spec), ...]) # K-split + merged heads + +def forward(ctx): # a TraceRunner variant + canvas, table = scatter_rows(pillar_rows, ctx["canvas_index"]) # [1,1,P,32] rows -> [1,1,H*W,32] TILE + blocks = backbone(FeatureMap(canvas, 1, 480, 480, 32)) + return head(neck(blocks)).tensor # one fp32 [1, 1, H*W, 32] tensor (15 channels used) +maps = head.unpack(runner("default", inputs=...), 480, 480) # host: {name: (C, H, W)} +``` + +| name | meaning | +|---|---| +| `gather.check_index(index, *, num_rows, sentinel=None)` | host validation of a gather index -> contiguous `uint32 [1, N]`; every entry in `[0, num_rows)` or equal to `sentinel`, else `ValueError` (an out-of-range index reads outside the table on the device) | +| `gather.gather_rows(index, table, *, sentinel=None, layout="tile", memory_config=None)` | `ttnn.embedding` of a UINT32 `[1, N]` index into a bf16 ROW_MAJOR `[1, 1, V, D]` table -> `[1, 1, N, D]`; with `sentinel` it is P4's fast `EmbeddingsType.PADDED` form (`padding_idx=sentinel`), which **returns the table's own row there**: the row must hold zeros | +| `gather.with_zero_rows(rows, count=1)` | `[1, 1, P, D]` rows (TILE or ROW_MAJOR) -> ROW_MAJOR table `[1, 1, P + count, D]` with zero rows appended (one `ttnn.pad`) | +| `gather.scatter_rows(rows, index, *, sentinel=None, layout="tile", memory_config=None) -> (canvas, table)` | the gather-form scatter: `canvas[n] = rows[index[n]]`, zeros where `index[n] == sentinel` (default `P`); static shapes, no canvas clear; P4: 0.21 ms at CP 480 x 480 | +| `gather.gather_rows_numpy`, `gather.scatter_rows_numpy(rows, index, *, sentinel)` | host oracles | +| `second.ConvSpec(weight, bias, stride=1, padding=None, relu=True, kind="conv"\|"conv_transpose", name="")` | one BN-folded layer: conv weight `[Cout, Cin, k, k]` (padding None = `k // 2`), ConvTranspose weight `[Cin, Cout, s, s]` (kernel == stride) | +| `second.Second(blocks, *, policy=None, prefix="backbone")` | SECOND: `blocks[i]` = list of 3x3 `ConvSpec` (block stride on the first); `__call__(fmap) -> [block outputs]` (input kept, inner layer outputs freed), `out_shapes(h, w)`, `release()`, `describe()`. C17 `Conv2d` layers: a DRAM input runs ttnn's automatic DRAM slicing (P14) | +| `second.SecondFPN(deblocks, *, policy=None, prefix="neck")` | one deblock per block output: `"conv"` 1x1 -> `RowLinear`; ConvTranspose k = 1 -> `RowLinear`, k = 2 -> `ttnn.conv_transpose2d`, k >= 3 -> linear + depth-to-space (C17 `ConvTranspose2d`, P5); every output moved to DRAM; the concat is never built | +| `second.RowLinear(weight, bias=None, *, activation=None\|"relu", precision=DEFAULT_PRECISION, output_dtype="bfloat16")` | a 1x1 conv / per-row dense layer: `ttnn.linear` on `[..., R, K]` TILE rows with an explicit compute config and `core_grid` from the device (keeps the ReLU fused), output DRAM; `weight` `[K, N]` or `[N, K, 1, 1]`; device weights uploaded on the first call | +| `second.DEFAULT_PRECISION` | C17's `CONV_PRECISION` (`HiFi4+fp32+l1acc`); a `ttaw.precision.PrecisionPolicy` overrides per module (`backbone.block.conv`, `neck.deblock`, `head.shared`, `head.hidden`, `head.out`); a precision's `activations` dtype (`:a=fp32`) is the dtype of that module's OUTPUT (bf16 by default; the K-split partial sums follow the shared conv's) | +| `second.free_maps(*maps)` | deallocate feature maps / tensors that still hold their buffer (`force=False`: views are left alone, P2) | +| `second.second_numpy(blocks, x_nchw)`, `second.second_fpn_numpy(deblocks, blocks_nchw)` | fp32 torch oracles (NCHW) | +| `centerhead.CenterHead(shared, split, heads, *, policy=None, prefix="head", output_dtype="float32", k_split=True, accumulate_dtype="bfloat16")` | `relu(conv3x3(concat(inputs)))` as a C17 `KSplitConv` over `split` (P14: 3.6 vs 14.8 ms at CP 480 x 480, more accurate), then the merged heads: `relu(x @ [Wh_1 \| ... \| Wh_n] + bh)` and the block-diagonal `@ Wo + bo` (two `RowLinear`s) -> ONE `[1, 1, H*W, C_pad]` tensor (`C_pad` = sum of head channels rounded up to 32). `shared_forward(inputs)`, `heads_forward(shared)`, `__call__(inputs)`, `unpack(rows, h, w) -> {name: (C, H, W)}`, `slices`, `release()`, `describe()` | +| `centerhead.merge_heads(heads, *, pad_to=32)` | host: `(Wh, bh, Wo, bo, slices)` of `[(name, hidden 1x1 + ReLU, final 1x1)]` (exact rewrite) | +| `centerhead.centerhead_numpy(shared, heads, inputs_nchw)` | fp32 torch oracle of the literal graph (concat, conv, n heads) | + +Device results (`common/tests/device/test_lidar_models_device.py`, TraceRunner: eager x2, strict capture, replay on a +new input, replay == eager bit for bit): the CP scatter at its real shape (40,000 rows into 480 x 480) bit-exact, +sentinel rows zero; CP-shaped SECOND (4 / 6 / 6 convs, 64 / 128 / 256 channels) + SECONDFPN + CenterHead with random +weights at 64 x 64 and 128 x 128 (first stride 1 and 2) PCC >= 0.999 for every block, deblock, the shared conv and +every head vs the torch fp32 oracle (`logs/ttaw/c19_c24_c25_device_results.json`). The CenterPoint bundle runs the same +modules with the real weights (`bundles/centerpoint-p150/PORT_LOG.md`). Host tests: +`tests/host/test_lidar_models_host.py` (13) on the fake ttnn plus `tests/host/fake_ttnn_lidar.py` (`embedding` with +P4's PADDED semantics, `max`, `EmbeddingsType`; `install(fake)` returns its undo). + +--------------------------------------------------------------------------------------------------------------------- + +## 19. grid_sample helpers (C23, `ttaw.ops.deform`) + +Built by the BEVDet port (PLAN.md C23; probe P9) for AlignBEV (8 history slots warped by per-frame affine grids) +and FPN_LSS's align_corners bilinear up-sampling; BEVFormer (DCN / rotate) and METEOR extend it. Grids are built on +the host (numpy, float32) and uploaded as ROW_MAJOR fp32 tensors (a per-frame RT-dev value or a static input); +`grid_sample` is the device call with the P9 rules checked first. + +```python +from .ttaw.ops import deform + +ring = runner.add_state("ring", shape=(8, 128, 128, 96), dtype="bfloat16", layout=ttnn.ROW_MAJOR_LAYOUT) # C % 32 +grid = deform.affine_grid(transforms_8x6, (128, 128), valid=[h >= 0 for h in history]) # [8, 128, 128, 2] fp32 +runner.add_param("grid", grid, shape=grid.shape, dtype="float32", layout=ttnn.ROW_MAJOR_LAYOUT) +aligned = deform.grid_sample(ctx["ring"], ctx["grid"]) # in a variant: bilinear, zeros, align_corners=False +up = deform.grid_sample(f2_rm, static_grid) # static_grid = deform.resize_grid((16, 16), (64, 64)) +``` + +| name | meaning | +|---|---| +| `pixel_to_grid(px, size)` | pixel coordinate (0 = first pixel centre) -> normalised `(2 px + 1) / size - 1` (float32): the align_corners=False form, exact for integer `px` when `size` is a power of two | +| `kernel_pixels(g, size)` | what the device kernel recovers: `g * size/2 + (size - 1)/2` in float32 (`grid_sample_reader_common.hpp`) | +| `affine_pixel_coords(transforms, out_hw)` | `ix = a w + b h + c`, `iy = d w + e h + f` per batch (float32, one rounding per op): the BEVDet AlignBEV pixel affine | +| `affine_grid(transforms [N, 6], in_hw, out_hw=None, *, valid=None)` | fp32 grid `[N, H, W, 2]`; `valid[n] == False` -> `OUTSIDE` (an exact zero sample: an empty history slot) | +| `resize_pixel_coords(in, out, align_corners=True)`, `resize_grid(in_hw, out_hw, *, align_corners=True, batch=1)` | static bilinear-resize grids (float64 source pixels, align_corners=False normalisation); for align_corners=True every source pixel is inside, so it equals `F.interpolate` up to the weight truncation | +| `padded_channels(c)`, `pad_channels(x)` | the input channel rule (multiple of 32; pad channels stay exactly 0 through the op) | +| `emulate_grid_sample(x, grid)` | host emulation of the kernel (fp32 fractions, weights **truncated** to bf16, taps outside skipped): the device test's oracle | +| `grid_sample(x, grid, *, compute_kernel_config=None, memory_config=None, batch_output_channels=False)` | `ttnn.grid_sample` bilinear / zeros / align_corners=False; refuses a TILE input or grid, input C % 32 != 0, a grid batch != input batch, a bf16 grid, and a FLOAT32 input with `fp32_dest_acc_en` (P9 defect); output DRAM by default | +| `OUTSIDE` | `-4.0`: a normalised coordinate whose four taps miss every input | + +Rules (P9): fp32 grids for every data-dependent grid (bf16 grids: PCC 0.9988 at 53 px, 0.992 at 128 px); C padded to +a multiple of 32; grids expanded per batch (no broadcast); ROW_MAJOR interleaved / height-sharded input and grid; +never a FLOAT32 input with `fp32_dest_acc_en`; call the op with align_corners=False on the align_corners=False +normalisation of the pixel coordinates you mean (zero padding acts in pixel space, so it is the same sampling as the +model's align_corners=True formulation, but integer coordinates stay exact: an identity warp is a bit-exact copy; +the literal ac1 normalisation leaves 2.8-7.6 % of values off by up to 1/32). The bilinear weights are truncated to +bf16 (0.33-0.6 % rrmse floor; K5 removes it); C18 `Resize2d` (fp32 interpolation matmuls) is the accurate +alternative for static resizes. + +Device results (`tests/device/test_deform_device.py`, TraceRunner: eager warm-up, strict capture, replay on new +data, replay == eager bit for bit; `logs/ttaw/deform_device_results.json`): AlignBEV [8, 128, 128, 96] identity slots +bit-exact, `OUTSIDE` slots exactly 0, pad channels 0, rigid-motion slots PCC >= 0.9999 vs torch fp32 and within 2 +bf16 ulps of `emulate_grid_sample`; the FPN_LSS resizes 16 -> 64 (640 ch) and 64 -> 128 (512 ch) PCC >= 0.99999 vs +`F.interpolate(align_corners=True)`, corners exact. Host tests: `tests/host/test_deform_host.py` (13). The BEVDet +bundle runs the same calls at its real shapes (`bundles/bevdet-p150/PORT_LOG.md`: AlignBEV moving slots PCC 0.999995 +vs the CPU reference). + +--------------------------------------------------------------------------------------------------------------------- + +## 20. ResNet builders (C27, `ttaw.models.resnet`) + +Built by the BEVDet port (PLAN.md C27) for its ResNet-50 image backbone (6 cameras as batch) and CustomResNet BEV +encoder; BEVFormer and METEOR reuse it. Built on the C17 builders of section 16 from BN-folded host weights; every op +traces, each conv prepares its device weights on its first (eager) call, every activation is a DRAM-interleaved TILE +`[1, 1, N*H*W, C]` map and intermediates are freed as soon as they are consumed. + +```python +from .ttaw.models import resnet as rn + +prov = lambda module: rn.ConvParams(w[module], b[module], stride, padding_tblr, dilation, groups) # BN folded +stem = rn.ResNetStem(prov, "img_backbone.conv1") # 7x7 s2 + ReLU + maxpool 3x3 s2 +r50 = rn.ResNetStages(prov, rn.mmdet_names("img_backbone"), [3, 4, 6, 3]) # bottleneck, pytorch style +c4, c5 = r50(stem(img_fmap), keep=(2, 3), free_input=True) # FPN inputs; the rest freed +bev = rn.ResNetStages(prov, rn.custom_resnet_names("img_bev_encoder_backbone"), [2, 2, 2], block="basic", + factory=rn.conv_factory("HiFi4+fp32+l1acc:w=fp32")) +f0, f1, f2 = bev(bev_in, keep=(0, 1, 2)) +``` + +| name | meaning | +|---|---| +| `ConvParams(weight [Cout, Cin/g, kh, kw], bias=None, stride=(1, 1), padding=(t, b, l, r), dilation=(1, 1), groups=1)` | one BN-folded conv as a provider returns it (numpy float32); a provider is `module name -> ConvParams` (BEVDet's reads `OnnxWeights` by consuming node, so no kernel size or stride is re-typed) | +| `conv_factory(precision=DEFAULT_PRECISION, **conv_kwargs)` | `(module, params, activation) -> callable`: one C17 `Conv2d` per module; `precision` a spec / `Precision` or a `PrecisionPolicy` resolved per module name. **DCN hook:** pass your own factory and return a deformable layer for the modules you name | +| `mmdet_names(prefix)`, `custom_resnet_names(prefix)` | `(stage, block) -> {conv1, conv2[, conv3], downsample, block}`: `layer{s+1}.{b}.conv{k}` / `.downsample.0`, or `layers.{s}.{b}.conv{k}` / `.downsample` | +| `Bottleneck(provider, names, *, has_downsample, factory)` | `relu(conv3(relu(conv2(relu(conv1(x))))) + idt)`, stride on `conv2` (pytorch style) | +| `BasicBlock(provider, names, *, has_downsample, factory)` | `relu(conv2(relu(conv1(x))) + idt)`; the projection may be any conv (CustomResNet: 3x3 stride 2) | +| `ResNetStem(provider, conv_module, *, factory=None, pool=True)` | `maxpool3x3s2p1(relu(conv1(x)))`; the pool runs DRAM-sliced and writes TILE | +| `ResNetStages(provider, names, layers, *, block="bottleneck"\|"basic", factory=None, downsample_first=())` | `__call__(x, keep=(), *, free_input=False) -> [kept stage outputs]` (input kept unless `free_input`; every other block output freed once consumed); `stages`, `convs()` | +| `maxpool_out_hw(h, w)`, `DEFAULT_PRECISION` (= C17 `CONV_PRECISION`) | helpers | +| `resnet_numpy(x_nchw, provider, names, layers, *, block, stem=None, keep=(), downsample_first=())` | fp32 torch oracle of the same blocks | + +Precision: the ports pick it. BEVDet runs `HiFi4+fp32+l1acc:w=fp32` (fp32 weights and biases: the bf16 rounding of +the BN-folded biases, applied per channel at every pixel, cost it depth PCC 0.9998 vs 0.99993 and 3 of the 52 sample0 +boxes, at no measured time cost); C17's `weight_terms=2` is the other accurate option. Device results +(`tests/device/test_resnet_device.py`, TraceRunner protocol; `logs/ttaw/resnet_device_results.json`): stem + two +bottleneck stages on [6, 3, 128, 352] and a CustomResNet stage (3x3 s2 projection) on [1, 864, 128, 128] -> 160, +random weights, PCC >= 0.999 vs `resnet_numpy` with both precisions, replay == eager bit for bit. Host tests: +`tests/host/test_resnet_host.py` (6, fake ttnn + `fake_ttnn_cnn` + a local max-pool fake). The BEVDet bundle runs the +real ResNet-50 / CustomResNet (`bundles/bevdet-p150/PORT_LOG.md`: depth / feat PCC 0.99994, chained heads >= 0.9995 +vs the fp32 CPU reference). + +--------------------------------------------------------------------------------------------------------------------- + +## 21. Query heads: top-k (C21 `ttaw.ops.topk`), heatmap peaks (C22 `ttaw.ops.heatmap`), TransFusion head (C26 `ttaw.models.transfusion_head`) + +Built by the TransFusion port (PLAN.md C21, C22, C26; probes P6, P7, P8, P13) for TF, BF and PT: everything after the +dense heatmap -- the 3x3 local maximum, the top-K proposal selection and the query decoder -- as one traceable device +graph with one packed output. numpy only at import. + +```python +from .ttaw.ops.heatmap import LocalMax, sigmoid_heat +from .ttaw.ops.topk import TopKSelect, selection_metrics +from .ttaw.models.transfusion_head import QueryHeadWeights, TransFusionQueryHead, assemble_transfusion + +local_max = LocalMax(192, 192, 5, rule="transfusion") # "bevfusion" / "ptv3": pooled_classes, passing cells +head = TransFusionQueryHead(QueryHeadWeights(...), prefix="decoder") # host numpy weights, BN folded +head.prepare(device) # tables + LayerNorm rows (before any capture) + +def forward(ctx): # a TraceRunner variant + heat, _ = sigmoid_heat(logits_fp32) # fp32 sigmoid -> bf16 (max_pool2d / top-k are bf16) + heat_nms = local_max(heat) # [1, 1, H*W, C] TILE + out = head(lidar_feat, heat_nms, ctx.get("topk_indices")) # None: device top-k; else teacher forcing + return pack_outputs(out) # heads (K x 32 fp32), query heat (Kp x 32), indices +raw = runner("default", inputs=...) +outs = assemble_transfusion(head.unpack_heads(raw["heads"]), raw["query_heat"], raw["indices"], bev_pos, + num_classes=5, num_proposals=500, cells=36864) # cls_score0 / bbox_pred0 / dir_cls_pred0 +``` + +| name | meaning | +|---|---| +| `heatmap.local_max_masks(h, w, classes, *, rule="transfusion"\|"bevfusion"\|"ptv3", pooled_classes=None, kernel=3)` | the constant masks `(m_pass, m_eq)` (NHWC rows `[h*w, classes]`, 0 / 1, disjoint) of `keep = m_pass + (heat == maxpool_kxk_s1_p(k//2)(heat)) * m_eq`: TF interior `m_eq`, no pass; BF pooled classes (default 0-3) as TF, the others pass everywhere; PT `m_pass = 1 - m_eq` (border and unpooled classes pass) | +| `heatmap.LocalMax(h, w, classes, *, rule, pooled_classes=None, kernel=3, memory_config="dram")` | the device chain on a bf16 TILE `[1, 1, h*w, classes]` heat (`max_pool2d` p1, `eq`, `multiply` by `m_eq` or `addcmul(m_pass, eq, m_eq)`, `multiply` by the heat); masks uploaded by the first call; `.numpy(heat_rows)` its host twin; refuses fp32 (max_pool2d is bf16 only) | +| `heatmap.sigmoid_heat(logits, *, dtype="bfloat16") -> (heat, sig)` | the sigmoid in the logits' dtype (fp32 logits: fp32 sigmoid), cast once; `sigmoid_heat_numpy` its host model | +| `heatmap.local_max_numpy`, `local_max_literal_numpy(heat_nchw, rule)` | oracles: the masked chain, and each model's literal `p0` + border / unpooled-class form | +| `topk.TopKSelect(cells, classes, k)` | `__call__(heat_nhwc) -> (indices, pos, cls)` (uint32 ROW_MAJOR `[1, padded_k(k)]`): `class_major_row` (transpose + untilize + reshape to one bf16 row, index `c * cells + p` = the ONNX `TopK` order), `topk_indices` (`topk_large_indices`, descending, ties unspecified), `decode` | +| `topk.decode_class_major(indices, cells, classes, *, clamp=True)` | exact decode with fp32 comparisons (`cls = sum_c idx >= c * cells`, `pos = idx - cls * cells`; no division), clamped so a 0xFFFFFFFF sentinel cannot become an out-of-range gather index; uint32 ROW_MAJOR rows for `ttnn.embedding` | +| `topk.padded_k(k)`, `K_MULTIPLE`, `MASK_VALUE` (-1e30), `SENTINEL` | k rounded up to a multiple of 16 (500 -> 512); mask scores with a finite value, never `-inf` (P8) | +| `topk.topk_numpy(scores, k)`, `class_major_numpy`, `decode_class_major_numpy`, `selection_metrics(dev_idx, ref_idx, *, reference_scores=None, flat_scores=None, strong=0.1)` | ONNX-semantics host top-k (ties to the lower index), layouts, and the set-based metrics of a device selection (`shared`, `strong_total` / `strong_kept` / `strong_overlap` / `strong_missed`) | +| `topk.local_max_margins(indices, heat, height, width, *, kernel=3)` (0.21.0) | per class-major proposal, the relative margin `(heat[p] - max same-class neighbour) / heat[p]` in the reference heat BEFORE the local max (1.0 without neighbours): the decisive / near-tie split of a strong-proposal gate (TransFusion gates margins > 0.5 %, reports the rest with `near_tie_report`) | +| `topk.topk_with_values(scores_tile, k)` | the bf16 `ttnn.topk` composite (values + indices, P8) | +| `transfusion_head.QueryHeadWeights(height, width, num_classes, num_proposals, class_table, bev_pos, self_posembed, cross_posembed, self_attn, cross_attn, norms, ffn, heads)` | model-agnostic host record (`MHAWeights`, `PosEmbedMLP`, `PredictionHead`; `[in, out]` layouts): `.validate()`, `.query_pos_table()` / `.key_pos_table()` (the position MLPs on `bev_pos`, float64), `.merged_heads()` | +| `transfusion_head.TransFusionQueryHead(weights, *, policy=None, prefix="head", attn_fp32_acc=False)` | `__call__(lidar_feat, heat_nms, indices=None, taps=None) -> {"heads", "query_heat", "indices"}`; pieces `init_queries`, `keys`, `decoder`, `predict`, `query_heat`; `unpack_heads(raw) -> {name: (c, K)}`; `prepare(device)`, `release()`, `describe()` | +| `transfusion_head.QueryHeadOracle(weights)` | the literal head in torch fp32 (posembed MLPs on `bev_pos[pos]`, unpadded attention, six heads) from NCHW maps and given indices: the device tests' reference | +| `transfusion_head.assemble_transfusion(heads, query_heat, indices, bev_pos, *, num_classes, num_proposals, cells)` | TF's (mmdeploy-patched) outputs on the host in float32: `cls_score0 = query_heat * sigmoid(heatmap)`, `bbox_pred0 = [center + query_pos, height, dim, vel]`, `dir_cls_pred0 = rot` | + +Device form of the head (every rewrite exact in real arithmetic; the oracle runs the literal forms): queries +`lidar_feat[pos] + class_table[cls]` (bf16 `ttnn.embedding` row gathers, uint32 indices from the exact decode); the +query position embedding is a function of `pos` only, so it is a constant **QPE table** `self_posembed(bev_pos)` +gathered by `pos` (`query_pos` itself, `k + 0.5` up to 191.5, never passes through bf16: S:transfusion:241); keys +`lidar_feat + KPE` with the constant `KPE = cross_posembed(bev_pos)`; head dim 16 -> 32 in the projection weights +(C20 `pad_head_columns` / `pad_head_rows`, exact), `scale` from the weights, C20 `sdpa` (non-causal, chunk table); +self-attention on the logical K queries with no mask (Q / K / V from one fused projection); LayerNorm with the +model's epsilon (`ttnn.layer_norm(o, residual_input_tensor=x, epsilon=...)`); merged heads (`relu(x @ [Wh_i]) @ +blockdiag(Wo_i)`, fp32 out). One decoder layer only (a second layer would re-embed the predicted centres: no constant +table). Precision `HiFi4+fp32:w=fp32` (`default_policy()`; per module `.self_attn` / `.cross_attn` / `.ffn` / +`.heads` / `.norm`). + +Device results (`tests/device/test_transfusion_head_device.py`, 13 cases through `TraceRunner`: eager x2, strict +capture, replay on a new input set, replay == eager bit for bit; watcher bring-up of the small shapes clean; +`logs/transfusion/m1/j2_ttaw_{small_watcher,full}.log`, results `logs/ttaw/c21_c22_c26_device_results.json`, gates +frozen in `test_transfusion_head_device.gates.json`): the masked local max is **bit-exact** against each model's +literal form at TF 192x192x5, BF 180x180x5 and PT 256x256x7 (plateaus and bright borders: ties everywhere); the +top-512 of TF 184,320 / BF 162,000 / PT 458,752 values has exactly the host's value multiset, unique in-range +indices in descending order, and an exact decode (also exhaustively over all 184,320 TF indices); surviving `-inf` +scores give 0xFFFFFFFF (22 of 32 in the canary) and the decode clamps them in range; the query head with random +weights, teacher-forced proposals, vs the literal fp32 oracle: TF (36,864 keys) PCC >= 0.9970 (queries 0.999998, +decoder layers >= 0.9996, heads >= 0.9970), BF (32,400 keys, the (i, j) `bev_pos`) >= 0.9922, query heat exact. +The TransFusion bundle runs the same modules with the deployed weights (`bundles/transfusion-p150/PORT_LOG.md`). +The selection chain at TF size (sigmoid, local max, class-major row, top-512, decode, one row gather) replays in +about 1.1 ms (`logs/transfusion/m1/exp1_full_*.log`: 2.0-2.4 ms for two chains). Host tests: +`tests/host/test_transfusion_head_host.py` (29) with `tests/host/fake_ttnn_query.py` (`topk_large_indices` with +HIGHEST-index ties, bf16-only `max_pool2d`, `layer_norm` with ttnn's 1e-12 default epsilon, `eq` / `ge` / +`subtract` / `addcmul`, an `embedding` that also records computed indices inside a capture). + +--------------------------------------------------------------------------------------------------------------------- + +## 22. Pillar feature net and input staging (C24 companion, `ttaw.models.pillars`) + +The PillarFeatureNet of the pillar detectors (CenterPoint, PointPainting, TransFusion) on the device and the host +staging of its two inputs. Promoted by the PointPainting port (ttaw 0.19.0) from the CenterPoint bundle's +`tt/pfn.py` + `FrameStaging` (device-verified there: PFN PCC 0.99997) with the TransFusion bundle's generalisation +(any hidden / output width; pillars of K < 32 points). ttaw 0.21.0 adds TransFusion's two-term PFN (`terms=2`) and +the TransFusion bundle runs on this module from then on; the CenterPoint bundle keeps its own copy until it re-vendors +and switches (its PORT_LOG notes it). + +```python +from .ttaw.models.pillars import FrameStaging, PfnPlan, TtPillarFeatureNet, features_shape, pack_inputs +from .ttaw.ops.gather import scatter_rows + +plan = PfnPlan.from_weights(w0, b0, w1, b1) # BN-folded [in, out] matrices: (F, H), (2H, O) +pfn = TtPillarFeatureNet(plan, num_pillars=40000, precision="HiFi4+fp32:w=fp32:a=fp32") # a= : hidden h / z dtype +runner.add_input("features", shape=features_shape(40000), dtype="bfloat16") # ROW_MAJOR, 1 KB / pillar +runner.add_input("canvas_index", init=np.full((1, H * W), 40000, np.uint32), dtype="uint32") + +def forward(ctx): # a TraceRunner variant + rows = pfn(ctx["features"]) # [1, 1, P, O] bf16 ROW_MAJOR + canvas, table = scatter_rows(rows, ctx["canvas_index"], sentinel=40000) # C19: NHWC [1, 1, H*W, O] TILE + ... +staging = FrameStaging(40000, H * W) # persistent host tensors, written in place per frame +out = runner("default", inputs=staging.write(features, canvas_index, num_pillars)) +``` + +| name | meaning | +|---|---| +| `PfnPlan.from_weights(w0, b0, w1, b1, *, in_padded=16)` | the device matrices of the identity-folded split PFN: `W0 (16, H_pad)`, `Wz = [I_H \| W1a \| 0] (H_pad, Z)`, `Wy = [W1b ; I_O ; 0] (Z, O)` (`H_pad` = H rounded up to 32, `Z` = H + O rounded up to 32); F <= 16, O % 32 == 0 (the C19 gather table). `.forward_numpy(features, *, hidden_round=None)`: its float32 host emulation (`hidden_round` models the hidden dtype) | +| `pfn_reference_numpy(features, w0, b0, w1, b1)` | the literal encoder in float64 (concat form; max over the given slots, padded slots included): the oracle | +| `TtPillarFeatureNet(plan, *, num_pillars, precision="HiFi4+fp32:w=fp32", name="pfn")` | `[1, 1, P, 32*16]` bf16 ROW_MAJOR -> `[1, 1, P, O]` bf16 ROW_MAJOR rows: reshape to `[1, 1, P*32, 16]`, tilize, `linear` W0 + ReLU, `linear` Wz, `max` over the 32 slots (dim -2), `linear` Wy + b1 + ReLU, untilize. HiFi4 required (the identity blocks); `Precision.activations` = the dtype of the hidden `h` / `z` (the output rows are always bf16); `.release()`, `.describe()` | +| `TtPillarFeatureNet(..., terms=2, bias_add=True)` (0.21.0), `TWO_TERM_PRECISION = "HiFi4+fp32:w=bf16"` | the two-term PFN (TransFusion's default): every linear a `TwoTermLinear` (weights / biases as bf16 `hi + lo`, products `hi@W_hi + hi@W_lo + lo@W_hi` with fp32 outputs), fp32 `h` / `z` / slot max split by `split_terms` before the next linear, bf16 output rows; `bias_add=True`: bias-free `RowMatmul` (`ttnn.matmul`, fp32 out) + one exact fp32 `ttnn.add` per bias (`ttnn.linear`'s fused bias rounds an fp32 output to ~11 bits on this tree); needs `w=bf16` | +| `split_terms(t)`, `RowMatmul(weight, *, precision, name)`, `TwoTermLinear(weight, bias=None, *, activation=None, precision=TWO_TERM_PRECISION, name, bias_add=True)` | the two-term building blocks (`split_terms`: fp32 -> bf16 `hi`, `lo = bf16(t - hi)`; also used by TransFusion's two-term SECOND convs) | +| `features_shape(P)` -> `(1, 1, P, 512)`; `pack_features(features (P_kept, K, F), P, *, out=None)` | the device input: one 1 KB row per pillar (32 slots x 16 features, zero-padded), rows past `P_kept` zero; **K < 32 slots: slots K..31 repeat slot 0** (TransFusion's 20-point pillars: the slot maxima are unchanged, zero rows would add `relu(b0)`) | +| `pack_inputs(features, canvas_index, num_pillars, *, capacity)` | `{"features", "canvas_index"}` as numpy (tests and tools); the index range-checked (C19 `check_index`, sentinel = `capacity`) | +| `FrameStaging(num_pillars, num_cells)` | persistent bf16 `features` / uint32 `canvas_index` host tensors (`tensors.HostStaging`); `.write(features, canvas_index, num_pillars=None)` converts only the kept pillars (torch fp32 -> bf16 RNE, K < 32 slot rule), zeroes the rows the previous frame used beyond them, copies the checked index and returns the `TraceRunner` inputs; `.zero_copy` (False: falls back to `pack_features` + `HostStaging.write`, same values) | + +Device form (exact rewrites, also in floating point): one pillar = one 32-row tile, so a slot max is a tile-column +reduction; `relu(. + c)` is monotonic, so the per-pillar term `c = m @ W1b + b1` is added after the max (no slot +broadcast); `h` and the max ride through the matmuls in identity blocks (x * 1.0 is exact with HiFi4). Every pillar +row is computed, also past the frame's pillar count: the scatter index never points there, so no count reaches the +device. Precision: the bf16 rounding of the hidden `h` / `z` is the PFN's largest error term (PointPainting's CPU +emulation on its golden frames: output rel. L2 0.0045 with bf16 hidden tensors, 0.0020 with fp32 hidden tensors and +TF32 weights, 0.0017 for the bf16 output rounding alone), hence the `a=fp32` option; a model with large-magnitude input +columns (absolute x / y up to 121.6 m) can rewrite its first layer around the pillar centre on the host (PointPainting +`tt/pfn_input.py`, a promotion candidate) and feed this module unchanged. + +Device results (`tests/device/test_pillars_device.py`, TraceRunner: eager x2, strict capture, replay on input set B, +replay == eager bit for bit; the 512-pillar cases first under `TT_METAL_WATCHER=2`, clean; random weights, bf16 +inputs, vs the literal float64 encoder on the same inputs; `logs/pointpainting/m1/j1_pillars_*.log`, results +`logs/ttaw/pillars_device_results.json`): CenterPoint widths (9 -> 16, 32 -> 32) PCC 0.999996 / rel. L2 0.0025; +PointPainting (16 -> 16, 32 -> 32) bf16 hidden 0.999996 / 0.0025, fp32 hidden 0.9999975 / 0.0024; TransFusion (11 -> +32, 64 -> 64, 20-point pillars) bf16 hidden 0.999995 / 0.0027, fp32 hidden 0.999997 / 0.0025; the real capacity +(40,000 pillars, 28,137 kept, fp32 hidden) 0.9999975; `FrameStaging`'s zero-copy path equals `pack_features` + bf16 +RNE for a large frame, a smaller one (its stale rows zeroed) and 20-point pillars. The PointPainting bundle runs it +with its real weights (PFN PCC 0.99999 on two golden frames, `bundles/pointpainting-p150/PORT_LOG.md`). Host tests: +`tests/host/test_pillars_host.py` (12; fake ttnn: the plan exact against the literal encoder for the CP / PP / TF +widths and the 20-slot rule, packing, the module through `TraceRunner` replay == eager with bf16 and fp32 hidden +tensors, `FrameStaging`'s fallback path). + +--------------------------------------------------------------------------------------------------------------------- + +## 23. Segment reductions: K1 `segment_reduce` and the log-step fallback (`ttaw.ops.segment`) + +Built by the FRNet port (PLAN.md 1.3 row K1; owned by it) for FRNet's six `ScatterElements(max)` sites (points +sorted by frustum cell); PTv3 pooling and BEVPool (sum, optimization phase) are of the same form once the host sorts +the rows. A *segmented* tensor holds rows sorted by segment id: segment `s` is the contiguous row range +`[off[s], off[s + 1])` (CSR offsets, non-decreasing); rows past `off[-1]` are padding that nothing reads. + +```python +from .ttaw.ops import segment as seg + +off = seg.segment_offsets(seg_id_sorted, num_segments) # host CSR offsets, uint32 [S + 1] +row = seg.check_offsets(off, num_segments=S, num_rows=N_cap, length=S + 1) # [1, K] for the device +k1 = seg.SegmentReduce(seg.SegmentReduceSpec(num_rows=N_cap, channels=128, num_segments=M_cap + 1, + input_dtype="float32", input_layout="tile", + output_dtype="bfloat16")) +runner.add_input("offsets", init=row, dtype="uint32") # RT-dev: rewritten per frame +def forward(ctx): # a TraceRunner variant + table = k1(point_rows_fp32_tile, ctx["offsets"]) # [1, 1, M_cap + 1, 128] bf16 ROW_MAJOR; empty rows -> 0 + return gather_rows(ctx["pix2vox"], table, sentinel=M_cap) # C19: straight into a gather table +``` + +| name | meaning | +|---|---| +| `SegmentReduceSpec(num_rows, channels, num_segments, input_dtype="float32", input_layout="tile", output_dtype="float32", op="max", empty_value=0.0, workers_per_core=2, unit_path=True)` | static shape of one call site (COMPILE). `num_rows % 32 == 0`, `channels % 32 == 0`; bf16 / fp32 in, TILE or ROW_MAJOR; bf16 (round to nearest even) / fp32 out; `unit_path` (0.23.4, TILE input): segments reduced 8 columns at a time in registers per 32-row unit (`False` = the 0.23.3 per-row accumulator path; both bit-exact); `op` `"max"` only on the device (`sum` / `mean` raise `NotImplementedError`: the data-movement RISC-Vs have no float unit, see below); `.l1_bytes_per_worker()`, `.check_l1(budget)` | +| `SegmentReduce(spec, *, name, grid=None)` | `__call__(x, offsets, *, output=None)` -> `[1, 1, num_segments, C]` ROW_MAJOR DRAM (allocated per call, or the persistent `output` of that spec): ONE `ttnn.generic_op`, eager or inside a capture. `x` `[1, 1, num_rows, C]` DRAM interleaved of the spec's dtype / layout; `offsets` uint32 ROW_MAJOR `[1, K >= num_segments + 1]` DRAM. `program(x, offsets, out)` (the `ProgramDescriptor`), `allocate_output(device)`, `output_spec()`, `describe()`. `grid` overrides the device grid (tests: one core) | +| `segment_reduce(x, offsets, *, num_segments, op="max", output_dtype=None, empty_value=0.0, output=None)` | one-shot form (spec from the tensors) | +| `logstep_segment_max(x, shift_tables, last_rows, *, layout="tile")` | the exact stock-op fallback (PLAN.md 1.3): `R` rounds `x = max(x, x[idx_r])` (untilize + `ttnn.embedding` + `ttnn.maximum`: 3 programs each), then a PADDED gather of `last_rows` from the result with a zero row appended at `R` (empty segments -> 0). bf16 in / out only (`ttnn.embedding` tables are bf16); exact for segments of up to `2^R` rows; `R` is COMPILE (bucket it per frame) | +| `segment_offsets(seg_id, num_segments, *, num_rows=None)`, `check_offsets(offsets, *, num_segments, num_rows, length=None)` | host CSR offsets from sorted ids (ids `>= num_segments` = trailing padding); validation (starts at 0, non-decreasing, ends `<= num_rows`) into the device `[1, length]` row | +| `segment_rounds(max_len)`, `segment_shift_tables(seg_id, rounds)`, `segment_last_rows(offsets, *, empty_row)` | the fallback's tables: `ceil(log2 L)`; `idx_r[i] = i - 2^r` in the same segment, else `i`; each segment's last row (`empty_row` = the row count: the appended zero row) | +| `segment_reduce_numpy(x, offsets, num_segments=None, *, op="max"\|"min"\|"sum"\|"mean", empty_value=0.0)`, `logstep_segment_max_numpy(x, shift_tables, last_rows)` | oracles (max / min exact in the input dtype; sum / mean in float64) | +| `worker_segments(offsets, num_segments, num_workers, *, num_rows=None)` | the kernel's work split, host twin (tests, diagnostics) | +| `OPS`, `DEVICE_OPS`, `KERNEL` | `("max", "min", "sum", "mean")`, `("max",)`, `"segment_reduce_dm.cpp"` | + +**Kernel** (`ops/kernels/segment_reduce_dm.cpp`, one source for both data-movement RISC-Vs of every core). Exact by +construction: the maximum is taken on integer keys of the float bit patterns (`key = bits ^ ((bits >> 31) & +0x7fffffff)`: signed order == float order, -0 < +0; NaN unsupported), so bf16 / fp32 results are bit-exact, and an +fp32 input with a bf16 output equals rounding first (RNE is monotonic). Work split without per-core runtime args +(probe P3 rule; common args = the three buffer addresses): worker `w` (= core index x 2 + RISC-V) owns the segments +whose cost `off[s] + s` (rows + one output row) lies in `[w T / W, (w + 1) T / W)`, found on the device by two binary +searches over the offsets (64-byte DRAM probes), so nothing in the host tables depends on the grid and ETH (12x10) +and WORKER (11x10) give identical outputs. Each worker streams its contiguous rows in units of 32 (one tile-row in +TILE mode; double-buffered NOC reads), reduces into an L1 accumulator and writes one output row per segment through +a ring of 8 staging rows; empty segments get `empty_value` (FRNet's frustum2pixel zero row comes out of the kernel). +Offsets are clamped to `[0, num_rows]` and to non-decreasing order, so a corrupt table cannot make it read outside +`x`. L1 per worker: 2 units + 1 KiB offsets window + 128 B probe + C x 4 B accumulator + 8 output rows (FRNet's +widest site, 256 fp32 channels: 75 KiB). Hang protocol (PLAN.md 4.4): no CB push / pop (CBs are plain scratch), no +multicast, no semaphores; DRAM reads keep the source's 64-byte alignment offset in L1 (Blackhole +`NOC_DRAM_READ_ALIGNMENT_BYTES`), every read is waited on (the barrier also invalidates the Blackhole L1 cache) +before use, staging rows are reused after `noc_async_writes_flushed`, and the kernel ends with both barriers. + +Why max only: the data-movement RISC-Vs (rv32im + Zba / Zbb, no F extension) compare integers natively (Zbb `max`) +but would emulate float adds in software; a `sum` / `mean` K1 needs the compute engine (the optimization-phase +consumers, PTv3 / BEVPool, add it with their device tests). + +Device results (`tests/device/test_segment_reduce_device.py`, the FRNet port's jobs; results +`logs/ttaw/k1_segment_reduce_device_results.json`): tiny bring-up under `TT_METAL_WATCHER=2` clean (64 x 32, 6 +segments incl. empty / 1-row / tile-row-crossing ones; one core with 1 and 2 workers; eager x2 and a 2-call trace +replayed on new data, bit-exact); FRNet's real sites through `TraceRunner` with the offsets rewritten per frame (10 +replays x 5 rewrites), every output bit-exact vs the oracle and replay == eager, 240 workers (12x10 ETH grid, 2 per +core): OT128 encoder site 160,000 x 256 fp32 -> 60,000 fp32 rows 5.52 ms per replay, OT128 point sites 160,000 x 128 +fp32 -> 60,001 bf16 rows 2.89 ms, QT128-like dense segments (6,255 segments, one of 500 rows) 2.22 ms, 2,048-row cases +0.04-0.08 ms; the log-step fallback equals K1 bit for bit (4 rounds on 4,096 rows; 7 rounds on 120,000 rows with +111-row segments) (`logs/frnet/m1a/j1_bringup_and_graph.log`, watcher log `logs/frnet/m1a/j1_tiny_watcher.log`, +`logs/ttaw/k1_segment_reduce_device_results.json`). Inside the FRNet graph (six sites per frame, OT128 sample): every +tap downstream PCC >= 0.9995 vs the fp32 reference (`bundles/frnet-p150/PORT_LOG.md`). A 2,000-launch soak +(`test_soak`) runs in the port's next job. Host tests: +`tests/host/test_segment_host.py` with `tests/host/fake_ttnn_segment.py` (program-descriptor records, a +`generic_op` that emulates the kernel from its compile-time args and checks the P3 rules and the split, `maximum`, +`hardswish`, `softmax`, `addcmul`). + +--------------------------------------------------------------------------------------------------------------------- + +## 24. Sparse-conv rulebooks (C13, `ttaw.sparse`) + +Built by the BEVFusion port (PLAN.md C13; owned by it) for BEVFusion's 21-layer sparse encoder and PTv3's +sub-manifold stages: the host side of the gather-GEMM sparse conv (C28). A sparse tensor is an active voxel set +`coords (N, 3)` = `(x, y, z)` in `spatial_shape (X, Y, Z)`; every spconv layer of the Autoware graphs +(`GetIndicePairsImplicitGemm` + `ImplicitGemm`, spconv 2.3.8) is a **gather**, for sub-manifold and strided layers +alike: `out[o] = sum_k W[:, k, :] @ in[nmap[o, k]]` (taps with `-1` contribute nothing), `W` the KRSC filter +`[Cout, k0, k1, k2, Cin]` (k0 along x), tap `k = (a * k1 + b) * k2 + c`. numpy only. + +```python +from .ttaw import sparse as sp + +l1 = sp.SparseLevel(coors_zyx[:, ::-1], (1440, 1440, 41)) # (x, y, z) rows = the feature rows +nm1 = sp.subm_neighbor_map(l1, 3) # (N1, 27) int32, spconv's 13-query rule +l2, d1 = sp.strided_neighbor_map(l1, 3, 2, 1) # next level + (N2, 27) gather map +bucket, overflow = sp.select_capacity(l2.num_active, (40_960, 147_456, 262_144)) +idx = sp.im2col_index(nm1, sentinel=cap, rows=cap) # (cap / 32, 27 * 32) uint32, tile-ordered +# device (C28): ttnn.embedding(idx, table [1, 1, cap + 1, Cin_pad], layout=TILE, padding_idx=cap, PADDED) +# -> experimental.view [1, 1, cap, 27 * Cin_pad] -> matmul [27 * Cin_pad, Cout] (BN folded) + ReLU +bev = sp.dense_gather_index(l_out, sentinel=n_out) # (Z, X * Y): one canvas gather per z slice +``` + +| name | meaning | +|---|---| +| `SparseLevel(coords, spatial_shape)` | an active set: exact int64 keys over the bounding box of grid + voxels (sorted keys + `searchsorted`, no aliasing, out-of-grid voxels allowed), duplicates refused; `.lookup(q) -> rows` (-1 = none), `.in_grid(q=None)`, `.linear_index()` (`(x * Y + y) * Z + z`), `.num_active`, `.describe()` | +| `subm_neighbor_map(level, kernel=3, dilation=1, *, rule="spconv"\|"exact")` | `(N, K)` int32. spconv uses `padding = (k // 2) * dilation` for sub-manifold layers. `"spconv"`: the 13-query + symmetric-write construction (`indices.py:1532,865,838-845`): a tap `k < K // 2` needs the **neighbour** inside the grid, a tap `k > K // 2` the **output voxel** inside it (S:ptv3:158); the centre tap is the voxel itself. `"exact"`: the plain lookup. Equal for in-grid voxel sets (every BEVFusion level); `"alias"` (PTv3's linear-key aliasing, S:ptv3:388) raises `NotImplementedError` until PTv3 adds it | +| `strided_neighbor_map(level, kernel, stride, padding, dilation=1) -> (out_level, nmap)` | regular sparse conv: `o` active iff some active `i = o * s - p + k * d` (`0 <= o < out_shape`); outputs in ascending linear-key order; one input per (output, tap); inputs must lie inside their grid | +| `conv_out_shape(shape, kernel, stride, padding, dilation=1)`, `kernel_offsets(kernel, dilation=1)`, `iter_taps(kernel)` | grid arithmetic `(in + 2p - d(k - 1) - 1) // s + 1`; tap offsets in tap order | +| `gather_index(nmap, *, sentinel, rows=None)` | `(rows, K)` uint32: `-1` and capacity rows -> `sentinel` (an explicit zero row of the table: C19's PADDED rule) | +| `im2col_index(nmap, *, sentinel, rows=None, block=32)` / `im2col_numpy(table, index, *, kernel_volume)` | the tile-ordered index `(rows / 32, K * 32)`, `index[b, k * 32 + v] = gather[b * 32 + v, k]`: a TILE `ttnn.embedding` of it into a `Cin % 32 == 0` table yields `[rows / 32, K * 32, Cin]` whose tiles, in memory order, are those of the `[rows, K * Cin]` im2col matrix (row `o` = its K tap rows concatenated, tap-major), so `ttnn.experimental.view` gives the matmul input (probe P4: 4.7 ms for 256k x 27 x 32); the oracle builds that matrix | +| `dense_gather_index(level, *, sentinel, split_axis=2)`, `dense_numpy(features, level)` | to-dense as gathers (`index[s, a * B + b]`, one canvas per slice of `split_axis`) and the ScatterND reference `[X, Y, Z, C]` | +| `select_capacity(count, buckets) -> (bucket, overflow)` | smallest bucket holding `count` (grid-independent constants, PLAN.md 0.2); the largest and `True` when none does | +| `sparse_conv_numpy(features, nmap, weight, bias=None)`, `dense_conv3d_numpy(features, level, weight, out_coords, *, stride, padding, dilation)` | oracles: the gather form (float64 accumulation) and a brute-force dense 3-D cross-correlation (Conv3d semantics) at the active outputs | +| `pairs_count(nmap)`, `neighbor_stats(nmap)` | rulebook size (FLOPs = 2 Cin Cout pairs), `{rows, pairs, mean_taps, max_taps}` | + +Facts (BEVFusion port): on the sample-rosbag frame #144 (98,334 voxels) every level's active count and every layer's +pair count equal the research reference's (`research/bevfusion/scripts/bevfusion_ref.py`, an independent +`index_add_` scatter form): 679,726 / 325,630 / 1,383,475 / 334,714 / 736,959 / 147,183 / 253,269 / 20,710 pairs for +subm1 / down1 / subm2 / down2 / subm3 / down3 / subm4 / conv_out; all four sub-manifold and four strided maps take +about 2.2 s in numpy on the shared host (a C++ / device builder is optimization work). Host tests: +`tests/host/test_sparse_host.py` (15): sub-manifold and strided maps equal a dense Conv3d at BEVFusion's layer +shapes, strided output sets equal the brute-force set, `"spconv"` equals a literal transcription of spconv's +construction also with out-of-grid voxels (where it differs from `"exact"`), the im2col tile order equals the im2col +matrix's for Cin 32 / 64 / 128, BEVFusion's level chain 1440x1440x41 -> 720x720x21 -> 360x360x11 -> 180x180x5 -> +180x180x2. C28 (the device gather-GEMM) is added with its device tests by the BEVFusion port's M1. + +--------------------------------------------------------------------------------------------------------------------- + +## 25. Gather-GEMM sparse encoder (C28, `ttaw.models.sparse_encoder`) + +Built by the BEVFusion port (PLAN.md C28; owned by it; probe P4) on the C13 rulebooks of section 24: every spconv +layer as ONE gather + ONE matmul on the device, any chain of sub-manifold / strided layers with basic-block residuals, +traceable, no count on the device. PTv3's sub-manifold stages are the second consumer. + +```python +from .ttaw import sparse as sp +from .ttaw.models.sparse_encoder import SparseConvSpec, SparseEncoder, dense_gather, pack_table + +specs = [SparseConvSpec("conv_input", w0, b0, "subm1", in_terms=2), # KRSC [Cout, k0, k1, k2, Cin], BN folded + SparseConvSpec("l1.conv1", w1, b1, "subm1"), + SparseConvSpec("l1.conv2", w2, b2, "subm1", residual="conv_input"), # relu(conv + b + identity) + SparseConvSpec("down1", w3, b3, "down1"), ...] +enc = SparseEncoder(specs, policy=policy, weight_terms=1) # fp32 weights (TF32-like, P12) +runner.add_input("vfe", pack_table(vfe, cap1, terms=2), dtype="bfloat16", layout=ttnn.ROW_MAJOR_LAYOUT) +runner.add_input("subm1", sp.im2col_index(nm1, sentinel=cap1, rows=cap1), dtype="uint32") # per index name +def forward(ctx): + y, table = enc(ctx["vfe"], {n: ctx[n] for n in enc.index_names}) # last fp32 output + its bf16 table + return dense_gather(table, ctx["dense0"]) # to-dense slice [1, 1, cells, C] +``` + +| name | meaning | +|---|---| +| `SparseConvSpec(name, weight, bias, index, residual=None, relu=True, in_terms=1, out_terms=1)` | one layer: `weight` KRSC (or `[Cout, K, Cin]`), `index` = the gather index name it reads (shared by the convs of a level), `residual` = an earlier layer's name; `.cin_pad` / `.cout_pad` (`terms * C` rounded up to 32), `.matrix()` (the `[K * cin_pad, cout_pad]` im2col weight), `.bias_row()`, `.lo_mask()` | +| `im2col_weight(weight3, *, cin_pad, cout_pad, in_terms, out_terms)` | host matrix: tap-major rows `k * cin_pad + j`; the `lo` channel block repeats the weights, `out_terms=2` repeats the columns | +| `TtSparseConv(spec, *, precision="HiFi4+fp32:w=fp32", weight_terms=1)` | `__call__(table, index, identity=None)` -> fp32 TILE `[1, 1, rows, cout_pad]`: TILE + PADDED `ttnn.embedding` of the tile-ordered `[rows / 32, K * 32]` index into the bf16 ROW_MAJOR `[1, 1, V + 1, cin_pad]` table (row `V` zero: the sentinel), `ttnn.experimental.view` to `[1, 1, rows, K * cin_pad]`, C24 `RowMatmul` (fp32 out; `weight_terms=2`: bf16 hi + lo weights, two matmuls), one exact fp32 bias add (+ the identity, ReLU fused into the last add); `gather(table, index)`; `to_table(y)` -> the next bf16 table (zero row appended; `out_terms=2`: `[bf16(y) \| bf16(y - bf16(y))]`) | +| `SparseEncoder(specs, *, policy=None, weight_terms=1, name="sparse")` | the chain (consecutive layers must agree on terms / widths, residual sources on the output layout); `__call__(table, indices, taps=None, keep_table=True) -> (y, table)`; `index_names`, `input_width`, `input_terms`; intermediate outputs freed after their last (residual) use unless tapped | +| `dense_gather(table, index)` | to-dense slice: C19 PADDED gather of a `[1, cells]` C13 `dense_gather_index` row -> `[1, 1, cells, C]` TILE | +| `pack_table(x, capacity, *, terms=1, width=None, out=None)`, `table_rows_numpy(x, *, terms, width)` | the first table on the host (`(1, 1, capacity + 1, width)` float32 with bf16-exact values; rows past `N` and the sentinel zero) | +| `sparse_layer_numpy(table, nmap, spec, *, identity=None)`, `sparse_encoder_numpy(specs, features, maps, *, round_tables=True)` | oracles (float64 matmul); `round_tables` models the device's bf16 / two-term tables, False is the fp32 network | + +**Activation terms.** `ttnn.embedding` is bf16-only, so every layer's input is rounded to bf16 once. A two-term +table (`in_terms=2`) carries `hi` and `lo = bf16(x - hi)` side by side in the channels (one gather, one matmul over +`[hi | lo] @ [W ; W]`); where `2 C <= 32` (a VFE input of 4 columns, BEVFusion's 16-channel level 1) the `lo` block +rides in channels the 32-wide table pads anyway. On BEVFusion's PandaSet frame the CPU emulation of the 21 layers +gives conv_out PCC 0.999995 with bf16 tables (fp32 weights), 0.999999 with two-term tables: the encoder is not the +precision bottleneck (BEVFusion PORT_LOG.md "Sparse precision"). + +Device results (`tests/device/test_sparse_encoder_device.py`, TraceRunner: eager x2, strict capture, replay on a +second frame, replay == eager bit for bit; the small cases first under `TT_METAL_WATCHER=2`, clean; +`logs/bevfusion/m1/j1_c28_small_watcher.log`, `j2_c28_bf.log`, results `logs/ttaw/c28_sparse_encoder_device_results.json`): +a 6-layer BEVFusion-shaped chain (220 voxels; two-term VFE, one- / two-term tables, fp32 and two-term weights) PCC +>= 0.99999 vs the oracle with the same table rounding; the 21-layer BEVFusion encoder with random weights (1440 x +1440 x 41 -> 180 x 180 x 2; 28.8 k / 37.5 k / 25.9 k / 14.0 k / 13.8 k active voxels in capacities 32,768 / 40,960 +/ 32,768 / 16,384 / 16,384) every layer PCC >= 0.99998, to-dense gathers bit-exact, **27.3 ms per replay** (21 +gathers + matmuls + table conversions + 2 to-dense gathers; first port, not optimized). Host tests: +`tests/host/test_sparse_encoder_host.py` (15; `tests/host/fake_ttnn_sparse.py`: a batch-form `embedding` and an +`experimental.view` that reinterprets TILE memory tile by tile, so the tile-ordered index order is checked). + +## 26. Page re-cut of ROW_MAJOR tensors: K12 `rerow` (`ttaw.ops.rerow`, 0.24.0) + +```python +from .ttaw.ops.rerow import rerow, rerow_plan +z = rerow(z, (1, 1, n * h2 * w2, c)) # == ttnn.reshape(z, ...) for a ROW_MAJOR DRAM-interleaved z +rs = Resize2d(in_hw, out_hw, channels=c, rerow="kernel") # the rm tail through rerow +``` + +| name | meaning | +|---|---| +| `rerow(t, shape, *, mode="kernel", joins=False)` | `ttnn.reshape(t, shape)` for a ROW_MAJOR DRAM-interleaved `t` and `shape = (1, 1, R, W)`: one data-movement `generic_op` (`kernels/rerow_rm.cpp`) when one page width is a whole multiple of the other and the small page is a multiple of 64 B, else `ttnn.reshape`; joins (small -> big pages) go to `ttnn.reshape` unless `joins=True` (slower there). Bit-identical (bytes copied) | +| `rerow_plan(rows_in, width_in, rows_out, width_out, elem_bytes, chunk_bytes=32768)` | the kernel plan (`RerowPlan`: direction, `m` small pages per big page, `k` per chunk, chunks) or None | +| `rerow_reference(stream, plan)` | host emulation of the kernel's page moves (tests): `(output stream, per-byte write count)` | +| `Resize2d(..., rerow="stock"\|"kernel")` | `kernel`: the `rm` tail `[N*H', W'*C] -> [N*H'*W', C]` through `rerow` (env `TTAW_RESIZE2D_REROW`) | + +Kernel: chunks of up to 32 KB inside one big page (one transfer on the big side, one per small page on the other), +split evenly over the device grid; one RISC / NOC per core issues the reads and the writes (SYS-1419), two L1 slots. +Device numbers: CHANGELOG 0.24.0 (splits 2x faster than ttnn's RM reshape at METEOR's shapes). diff --git a/code/tt_depthpro2/ttaw/VENDORED.json b/code/tt_depthpro2/ttaw/VENDORED.json new file mode 100644 index 0000000000000000000000000000000000000000..847bf91c831c99580bd6ad5119c41e0e63564b3f --- /dev/null +++ b/code/tt_depthpro2/ttaw/VENDORED.json @@ -0,0 +1,59 @@ +{ + "package": "ttaw", + "version": "0.24.3", + "source": "common/ttaw", + "source_commit": "1d954bf1142b1334710f4656f4e234b4f33eedee", + "source_ref": "HEAD", + "source_tree": "commit", + "source_dirty": false, + "vendored_at": "2026-11-28T16:18:14+00:00", + "files": { + "API.md": "b4d4c324ee8a38cd8b259c2d53bce3759214fb9f14eeea362b0b8c9addac397b", + "__init__.py": "9deb338b70e52f5fc1c52536cf1d193ed8e986116a5164ad5b0f9a147c5e277e", + "api_base.py": "189ee4215f937b812afee40d076bb948861a489e0b9e42a102bba311e0536179", + "decode.py": "f8aa2efa7ec664da7b8af94bed2d5771552b08b1a6d0bf97cbafcd18ea805c90", + "device.py": "69f41accfd3320395453ebb5c8f8c2b90ee52ec28d3211ac6750646fce51fe54", + "geometry.py": "087dcf7f43ef187fb051a504fe15365985c2c543eb3e05554a9017bcef90fcd5", + "golden.py": "d675431f052bfd01438aa79d3a5e281380a498b1f762e70b0ae0f3b4f194c7ad", + "image.py": "0a755647744d15f84077fe396d2514ba996a3ca056d172327874df2f21b52d76", + "image_area.py": "8d9e171167cf3fe2b59505ae9e5661cf1c032e21f282aa3e78361b4140e3d98c", + "image_linear.py": "debd3ade236a69f74859ae91ac9013c4757198ac29508f06f85d195c38e49d31", + "image_triangle.py": "b3f2f08a3c2512c4df28b987d8002358ef5b7556bc1ad29f5b91c956b7d154c2", + "io.py": "c2ac25cb589351a47b26688759d198204b5f0c25fd92f2a5c1c6428cea5a149e", + "knobs.py": "888783782c8f2e230538f416c360791f5cf8b21e5330414596fda7898308a279", + "metrics.py": "6d3a6b36d287aba05537b57d3c7560fd93537063e6b5c592492ed7d6e410e9e0", + "models/__init__.py": "40fb7b5d4bb07ccef5c739868b4d6260d9c82e4dfaefc8ecf1d94b23c083a4d8", + "models/centerhead.py": "0f404b39b5f063e8d29e546887e03c3681630d1f4d98fffab693c501fc92cff6", + "models/pillars.py": "e526d60010824a2a58d04cbf94cf446e2301eba39d1f5a6a9e4c8cd87ca0f3a1", + "models/resnet.py": "51183499e25f8146c68a417d2ac1a176c8f941ca224b58609c34bb356fe500b0", + "models/second.py": "8e98236f9903c8ce52b79ccc18869b5a8cccae8401baa9f2294c4dd2d7b2111d", + "models/sparse_encoder.py": "002c29d1338de200337f5012733e3d688ab877d72bab000824fb0a85de3a97e2", + "models/transfusion_head.py": "c3ffaae100d7154fd1b28562c64aaca27dddcfe81460792675576a5c2433dbbf", + "nms.py": "c3c9e63b201c68211fcb6a9a2844e63f7233212354e9b61eb869d9ae12097116", + "ops/__init__.py": "6d6aa15abd7f3cded433e083988a6f420f351e2bf0d7765d9e8c9c05d26fec64", + "ops/attention.py": "73e170cbd483590de08867881a282816b28d359bde91ff70de93dec6c786e404", + "ops/conv.py": "d8c5a31ef710aeb9568e638b721d4255f63743a1b88f822e6f411dee4e158532", + "ops/deform.py": "ac10088af29bc83fd66fab02712c836ffa5795ec4f7304846722ca54181897cd", + "ops/gather.py": "e2934f898b49088c387e8e89db31681257cdba03204efbee4160e055a38f0280", + "ops/heatmap.py": "05f13986f0ed7c59e1d80877ab5ca8cca7528e30c60e43dc489086f58732f596", + "ops/kernels/rerow_rm.cpp": "30b475508d42c7f4404cecca8089bafd06c84db62eed46e96a7240155ed2fc3f", + "ops/kernels/segment_reduce_dm.cpp": "cf45639cd596e18a1ccfaccf90d02bdfddc12dec4bf16a2d3d84deede01dbba3", + "ops/rerow.py": "ab00503c7bf4190babf11b50db2c912f5780ac6160f948d6fdb689c45f5dda84", + "ops/segment.py": "2ad0946c46419f70163ca51351b7e9e9aa7c35b1a7d6bbcb230c10d0d6039950", + "ops/topk.py": "bdfee6145e5ec19dc62fa115a19482fed4966c215155ec599783ac58d76f0f2e", + "ops/upsample.py": "030f1c320b6bddc5c33003d81efd40160ad3fd55f8e0178d50da6914f9539304", + "outputs.py": "e345695de6a888ee617afbb1a79bfd4251e768a31446fadf7d2ca6aba330d6ca", + "pointcloud.py": "fba6368408de16d258946b2814e7e1e286495c870750dafe52c92f7eec985758", + "precision.py": "8a01f1d048c3d317cc3caa095421e9695c2f6b7fdad2623a8d0c26364bdeaf3d", + "profiling.py": "c65aefbf0c2df111246f927f20220619686c51ad3b959ddb030655e97d8461f4", + "server/__init__.py": "3bbfe7beb80bf1b7a983c264e1ae3f08e162da17289b397ff0c4f425bb4e689a", + "server/app.py": "23cbf230d7393f743527fda1706f180c90fb8c6c2089fbf6559bd29d10d951dc", + "server/client.py": "e78f07ebdb132cb06c069259903dc7f971044f75f4918aacd184e5a59d7ca987", + "server/smoke.py": "acc547a03bcfe719ca1b5fba4e551d0dadecf77505f8e39848747b32c082b33b", + "sparse.py": "80359cdb020b3dd41d3fd6551502b98105c1f0642d89c3323769856629bab1a8", + "tensors.py": "a1a9f297aca23c1868e52b2bde73582596d8030516958f709183284723bc3280", + "trace.py": "c368eacec88027ca32f2caf977ef724dd1044230674350159a20b841b75c0a1d", + "voxelize.py": "88183715a10be92d489d35acf88defa4eaf47763fcb0356a71d64d97acc859b6", + "weights.py": "c8857817b7273e48278bb8194cece7fc38d99722119caacf8eb8fb8689648fad" + } +} diff --git a/code/tt_depthpro2/ttaw/__init__.py b/code/tt_depthpro2/ttaw/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d30eb2060c99c2f2b0a46e79b4307de8bd2f3bd --- /dev/null +++ b/code/tt_depthpro2/ttaw/__init__.py @@ -0,0 +1,106 @@ +# SPDX-License-Identifier: Apache-2.0 +"""ttaw: shared infrastructure of the Autoware ports to one Tenstorrent Blackhole p150 (ttnn / tt-metalium). + +The package is the source of truth under ``common/ttaw`` and is vendored into every bundle as the sub-package +``code//ttaw`` by ``common/tools/vendor.py``. Rules that keep one tree valid in both places: + +- relative imports only (``from .device import open_device``), never ``import ttaw``; +- importing any module has no side effects: no ``import ttnn`` / ``torch`` at module level, no device, no network, + no environment reads (ttnn and torch are imported inside the functions that need them); +- optimization knobs are read once at model build (:mod:`.knobs`) and each has an env A/B switch; +- custom kernel ``.cpp`` files are package data, located with :func:`.ops.kernel_path`. + +Modules (see ``API.md`` for the full guide): + +================== ====== ============================================================================= +module id what it provides +================== ====== ============================================================================= +``device`` C01 ``open_device`` (ETH dispatch default, ``auto`` patch detection), ``describe_device`` +``trace`` C02 ``TraceRunner``: persistent I/O, warm-up, capture, variants, 1CQ / 2CQ, state +``tensors`` C03 tile padding, layout / dtype helpers, fp32 islands, zero-copy host staging buffers +``weights`` C04 ``OnnxWeights``, BN folding in fp64, safetensors / ``.pth`` loading, weight cache +``precision`` C05 explicit ``compute_kernel_config`` factory and per-module policy tables +``knobs`` -- env A/B knobs read once at build +``metrics`` C06 PCC variants, argmax agreement, IoU, top-K overlap, detection matching, ADE/FDE +``golden`` C06 golden ``.npz`` files, tap registry, gate registry that never loosens, reports +``profiling`` C07 stage bench (p50/p99), Tracy signposts, ops-CSV summarizer, AICLK sampler +``io`` C08 point cloud / image / calibration decoding, output encoders +``outputs`` C08 ``Detections3D`` ``Detections2D`` ``Segmentation3D`` ``Mask2D`` ``Trajectory`` +``api_base`` C08 ``ModelBase`` (from_pretrained, weights resolution, warm-up, lock, info, close) +``server`` C08 FastAPI app factory (``server.app``); stdlib client, smoke and reference checks + (``server.client``, ``server.smoke``) +``image`` C14 bit-exact Autoware image pre-processing from cached LUTs (YOLOX letterbox, BEVDet crop) +``image_area`` C14 METEOR preset: OpenCV ``INTER_AREA`` down-scaling of uint8 frames, bit-exact +``image_linear`` C14 SceneSeg preset: OpenCV ``INTER_LINEAR`` / ``INTER_NEAREST`` resizes of uint8 frames and the + VisionPilot normalisation (BGR / RGB), bit-exact +``image_triangle`` C14 StreamPETR preset: Autoware's anti-aliased triangle resize + crop + normalise kernel, + bit-exact (normalisation presets autoware_main / autoware_0.52 / awml_training) +``geometry`` C10 rigid transforms (float64), Autoware's float32 sweep transform, yaw conventions +``pointcloud`` C11 Autoware multi-sweep densification state machine (per stream), hygiene masks +``voxelize`` C12 deterministic pillars, 9/10/11-feature decoration, canvas scatter / gather index +``sparse`` C13 sparse-conv rulebooks: spconv-faithful sub-manifold / strided neighbour maps (gather + form), tile-ordered im2col and to-dense gather indices, capacity buckets, oracles +``nms`` C15 circle NMS, perception_utils IoU-BEV NMS, area class remapper +``decode`` C16 CenterHead dense decode (and at given cells), Autoware DetectedObject mapping +``ops`` -- kernel package-data helpers (custom ``generic_op`` kernels live in ``ops/kernels``) +``ops.conv`` C17 conv2d builders (weights prepared once, fused activations, DRAM slicing), K-split, + ConvTranspose k == s, feature-map glue +``ops.upsample`` C18 nearest up-sampling, ``F.interpolate`` matrices, separable device resize +``ops.attention`` C20 SDPA wrapper (non-causal, explicit scale, chunk table, aligned masked keys), heads +``ops.gather`` C19 gather-form scatter (zero sentinel row + TILE / PADDED ``ttnn.embedding``), row gathers +``ops.topk`` C21 top-k proposal selection (class-major ``topk_large_indices`` row, exact decode, set metrics) +``ops.heatmap`` C22 sigmoid + 3x3 local max of TF / BF / PT heatmaps (one exact masked chain) +``ops.deform`` C23 grid_sample helpers: fp32 affine / resize grids (exact identity), P9 rules, kernel emulation +``ops.segment`` K1 per-segment max over rows sorted by segment (``generic_op`` kernel, exact, no + per-core args), the log-step stock-op fallback, CSR / shift tables, oracles +``models`` C24 C25 device sub-networks: ``models.second`` (SECOND + SECONDFPN), ``models.pillars`` + C27 C26 (PillarFeatureNet + its input staging), ``models.centerhead`` (CenterPoint dense + head: K-split shared conv, merged heads), ``models.resnet`` (ResNet + bottleneck / basic-block builders, cameras as batch), ``models.transfusion_head`` + (TransFusion query head: selection, query init, decoder layer, merged heads) +================== ====== ============================================================================= +""" + +__version__ = "0.24.3" + +__all__ = [ + "__version__", + "api_base", + "decode", + "device", + "geometry", + "golden", + "image", + "image_area", + "image_linear", + "image_triangle", + "io", + "knobs", + "metrics", + "models", + "nms", + "ops", + "outputs", + "pointcloud", + "precision", + "profiling", + "server", + "sparse", + "tensors", + "trace", + "voxelize", + "weights", +] + + +def __getattr__(name: str): + """Load submodules on first attribute access (``ttaw.trace``), keeping ``import ttaw`` free of side effects.""" + if name in __all__ and name != "__version__": + import importlib + + return importlib.import_module(f".{name}", __name__) + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +def __dir__(): + return sorted(set(globals()) | set(__all__)) diff --git a/code/tt_depthpro2/ttaw/api_base.py b/code/tt_depthpro2/ttaw/api_base.py new file mode 100644 index 0000000000000000000000000000000000000000..abee4fc03eec88d852e5b832f2c6b6ae8d41715b --- /dev/null +++ b/code/tt_depthpro2/ttaw/api_base.py @@ -0,0 +1,383 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C08 ``ModelBase``: the Python API contract shared by every bundle (BUNDLE_CONVENTIONS.md section 8). + +A bundle's ``api.py`` subclasses :class:`ModelBase`, sets the identity class attributes and implements six hooks:: + + class CenterPoint(ModelBase): + MODEL_NAME = "centerpoint-p150" + ENV_PREFIX = "CENTERPOINT" + DEFAULT_REPO = "AutowareFoundation/lidar_centerpoint" + DEFAULT_TAG, DEFAULT_REVISION = "v4.1", "494c8171def40bd36cc2feb323e0a5acbfab132b" + ALLOW_PATTERNS = ["base/*", "tiny/*"] + VARIANTS, DEFAULT_VARIANT = ("base", "tiny"), "base" + LABELS = ("CAR", "TRUCK", "BUS", "BICYCLE", "PEDESTRIAN") + RUNTIME_PARAMS = {"score_threshold": (float, 0.0, 1.0, 0.35)} + DEVICE_DEFAULTS = {"num_command_queues": 1, "trace_region_size": 64 << 20} + + def _build(self): ... # weights -> device tensors, TraceRunner + variants (no capture) + def _warm_one(self, v): ... # capture the variant's traces (TraceRunner.capture) + def _prepare(self, **kw): ... # host pre-processing -> host buffers + def _forward(self, prep): ... # upload + replay + read (under the model lock) + def _postprocess(self, raw, prep, params): ... # -> an ttaw.outputs object + def _release(self): ... # TraceRunner.release() + +Contract: ``from_pretrained`` resolves the pinned weights *before* opening the chip (a Hub problem must not claim +the device), opens it (ETH dispatch, 12x10), builds, and warms every default variant, so the first call is as fast +as the next. Calls are serialized by a re-entrant lock; ``close()`` is idempotent and also runs at interpreter exit. +Importing this module has no side effects (no ttnn, no torch, no network). +""" +from __future__ import annotations + +import atexit +import logging +import math +import os +import threading +import time +import weakref +from pathlib import Path +from typing import Any, ClassVar, Dict, List, Mapping, Optional, Sequence, Tuple + +import numpy as np + +from . import io as tio +from .device import DeviceConfig, close_device, describe_device + +__all__ = ["ModelBase", "resolve_weights"] + +log = logging.getLogger(__name__) + +# the input keyword arguments of ModelBase.__call__ (never runtime params) +_CALL_INPUTS = ("points", "sweeps", "images", "calibration", "stream", "inputs") + + +def resolve_weights(model_id: str, *, revision: Optional[str] = None, allow_patterns: Optional[Sequence[str]] = None, + weights_dir: Optional[str] = None, env_var: Optional[str] = None) -> Path: + """Local directory holding the weights files. + + Order: ``weights_dir`` > ``$`` > ``model_id`` if it is a local directory > the Hugging Face snapshot of + ``model_id`` at ``revision`` restricted to ``allow_patterns``. If the Hub is unreachable the cached snapshot is + used (``local_files_only=True``). Never needs a token for public repos; never uploads.""" + for cand in (weights_dir, os.environ.get(env_var) if env_var else None): + if cand: + p = Path(cand).expanduser() + if not p.is_dir(): + raise FileNotFoundError(f"weights directory {p} does not exist") + return p + if Path(model_id).expanduser().is_dir(): + return Path(model_id).expanduser() + from huggingface_hub import snapshot_download + + patterns = list(allow_patterns) if allow_patterns else None + try: + return Path(snapshot_download(model_id, revision=revision, allow_patterns=patterns)) + except Exception as e: # noqa: BLE001 -- offline or rate limited: fall back to the local cache + log.warning("Hub not reachable for %s@%s (%s: %s); trying the local HF cache", model_id, revision, + type(e).__name__, e) + return Path(snapshot_download(model_id, revision=revision, allow_patterns=patterns, local_files_only=True)) + + +_LIVE: "weakref.WeakSet" = weakref.WeakSet() + + +@atexit.register +def _close_all() -> None: + """A model that was not closed is closed when Python exits, so the chip is left clean.""" + for model in list(_LIVE): + try: + model.close() + except Exception: # noqa: BLE001 -- best effort at exit + pass + + +class ModelBase: + """Base class of every bundle's model class. Create instances with :meth:`from_pretrained`.""" + + # ---- identity (override in the bundle) --------------------------------------------------------------------- + MODEL_NAME: ClassVar[str] = "model" + ENV_PREFIX: ClassVar[str] = "MODEL" # _WEIGHTS_DIR, _DISPATCH, _NUM_CQS, ... + DEFAULT_REPO: ClassVar[str] = "" + DEFAULT_TAG: ClassVar[Optional[str]] = None + DEFAULT_REVISION: ClassVar[Optional[str]] = None # the commit DEFAULT_TAG points to (tags can move) + ALLOW_PATTERNS: ClassVar[Optional[Sequence[str]]] = None + WEIGHTS_LICENSE: ClassVar[str] = "Apache-2.0 (AutowareFoundation model card)" + VARIANTS: ClassVar[Sequence[str]] = ("default",) + DEFAULT_VARIANT: ClassVar[str] = "default" + INPUT_KIND: ClassVar[str] = "lidar" # lidar | camera | multicam | lidar+multicam | planner + CAMERA_ORDER: ClassVar[Sequence[str]] = () + REQUIRE_CALIBRATION: ClassVar[Optional[bool]] = None # None: True for multicam / lidar+multicam + POINT_FIELDS: ClassVar[Sequence[str]] = tio.DEFAULT_POINT_FIELDS + LABELS: ClassVar[Sequence[str]] = () + # name -> (type, min, max, default): host-side knobs only (BUNDLE_CONVENTIONS.md section 9); min / max may be + # None for an open side + RUNTIME_PARAMS: ClassVar[Mapping[str, Tuple[type, Any, Any, Any]]] = {} + # model-specific input keyword arguments passed to _prepare (not runtime params), e.g. PointPainting ("rois",): + # the server's ServerSpec.decode_extra adds them to the call kwargs + EXTRA_INPUTS: ClassVar[Sequence[str]] = () + # planner-style named inputs: name -> (shape with None for free dims, dtype); when set, ``inputs=`` is decoded + # and checked with io.load_named_arrays on every call (API and server alike) + INPUT_SCHEMA: ClassVar[Optional[Mapping[str, Tuple[Sequence[Optional[int]], Any]]]] = None + # defaults for ttaw.device.DeviceConfig; _* environment variables override them + DEVICE_DEFAULTS: ClassVar[Mapping[str, Any]] = {} + + def __init__(self, *_args: Any, **_kwargs: Any): + raise TypeError(f"use {type(self).__name__}.from_pretrained(...)") + + # ---- weights / device ------------------------------------------------------------------------------------ + @classmethod + def requires_calibration(cls) -> bool: + if cls.REQUIRE_CALIBRATION is not None: + return bool(cls.REQUIRE_CALIBRATION) + return cls.INPUT_KIND in ("multicam", "lidar+multicam") + + @classmethod + def resolve_weights(cls, model_id: Optional[str] = None, revision: Optional[str] = None, + weights_dir: Optional[str] = None) -> Path: + """:func:`resolve_weights` with this model's defaults (pinned revision for the default repo).""" + model_id = model_id or cls.DEFAULT_REPO + rev = revision or (cls.DEFAULT_REVISION if model_id == cls.DEFAULT_REPO else None) + return resolve_weights(model_id, revision=rev, allow_patterns=cls.ALLOW_PATTERNS, weights_dir=weights_dir, + env_var=f"{cls.ENV_PREFIX}_WEIGHTS_DIR") + + @classmethod + def device_config(cls, **overrides: Any) -> DeviceConfig: + """``DEVICE_DEFAULTS`` < ``_*`` / ``TT_DEVICE_ID`` environment < explicit non-None ``overrides`` + (``device_id``, ``dispatch``, ``num_command_queues``, ...).""" + base = DeviceConfig.from_env(cls.ENV_PREFIX, **dict(cls.DEVICE_DEFAULTS)) + values = {k: getattr(base, k) for k in base.__dataclass_fields__} + values.update({k: v for k, v in overrides.items() if v is not None}) + return DeviceConfig(**values) + + @classmethod + def from_pretrained(cls, model_id: Optional[str] = None, *, revision: Optional[str] = None, + variant: Optional[str] = None, device_id: Optional[int] = None, device: Any = None, + dispatch: Optional[str] = None, num_command_queues: Optional[int] = None, + weights_dir: Optional[str] = None, warmup_variants: Any = "default", verbose: bool = False, + **compile_params: Any) -> "ModelBase": + """Resolve weights, open the chip (unless ``device`` is given; ``close()`` then leaves it open), build the + graph and capture the traces of ``warmup_variants`` (``"default"``, ``"none"`` or a list). + + ``variant``: one of ``VARIANTS`` (load-time; default ``_VARIANT`` or ``DEFAULT_VARIANT``). + ``device_id``: default ``TT_DEVICE_ID`` or 0. ``dispatch``: ``"eth"`` / ``"worker"`` / ``"auto"`` (default + ``_DISPATCH`` or eth). ``num_command_queues``: default ``_NUM_CQS`` or ``DEVICE_DEFAULTS``. + ``compile_params``: shape-defining options, validated in ``_build``.""" + variant = variant or os.environ.get(f"{cls.ENV_PREFIX}_VARIANT") or cls.DEFAULT_VARIANT + if variant not in cls.VARIANTS: + raise ValueError(f"variant={variant!r}: expected one of {list(cls.VARIANTS)}") + clash = sorted(set(cls.RUNTIME_PARAMS) & (set(_CALL_INPUTS) | set(cls.EXTRA_INPUTS))) + if clash: + raise TypeError(f"{cls.__name__}: RUNTIME_PARAMS {clash} clash with input keyword arguments") + self = cls.__new__(cls) + self._lock = threading.RLock() + self._closed = False + self._owns_device = device is None + self.device = None + self.variant = variant + self.compile_params = dict(compile_params) + self.verbose = verbose + self.warmup_ms: Dict[str, float] = {} + self.warm_variants: List[Any] = [] + self.device_info: Dict[str, Any] = {} + model_id = model_id or cls.DEFAULT_REPO + rev = revision or (cls.DEFAULT_REVISION if model_id == cls.DEFAULT_REPO else None) + t0 = time.perf_counter() + log.info("Loading weights %s@%s (variant %s)", model_id, rev, variant) + self.weights_path = cls.resolve_weights(model_id, revision, weights_dir) + self.weights = {"repo": model_id, "tag": cls.DEFAULT_TAG if model_id == cls.DEFAULT_REPO else None, + "revision": rev, "path": str(self.weights_path), "license": cls.WEIGHTS_LICENSE} + self.warmup_ms["weights"] = (time.perf_counter() - t0) * 1e3 + try: + if device is None: + cfg = cls.device_config(device_id=device_id, dispatch=dispatch, num_command_queues=num_command_queues) + log.info("Opening device %d (dispatch %s, %d CQ)", cfg.device_id, cfg.dispatch, cfg.num_command_queues) + device = cfg.open() + device_id = cfg.device_id + self.device = device + self.device_info = describe_device(device, device_id) + t1 = time.perf_counter() + self._build() + self.warmup_ms["build"] = (time.perf_counter() - t1) * 1e3 + self.warmup(warmup_variants) + except BaseException: + self.close() + raise + self.warmup_ms["total"] = (time.perf_counter() - t0) * 1e3 + _LIVE.add(self) + return self + + # ---- warm-up --------------------------------------------------------------------------------------------- + def default_warmup_variants(self) -> List[Any]: + """The trace variants captured by default (e.g. pillar-count buckets). Override per port.""" + return [{"variant": self.variant}] + + def warmup(self, variants: Any = "default") -> Dict[str, Any]: + """Compile + capture each variant (idempotent). Returns ``{"ms": ..., "variants": [...]}``.""" + self._check_open() + if variants == "default": + todo = self.default_warmup_variants() + elif variants in (None, "none"): + todo = [] + else: + todo = list(variants) + t0 = time.perf_counter() + with self._lock: + for v in todo: + if v in self.warm_variants: + continue + log.info("Warming up: capturing trace for %s", v) + self._warm_one(v) + self.warm_variants.append(v) + ms = (time.perf_counter() - t0) * 1e3 + self.warmup_ms["warmup"] = self.warmup_ms.get("warmup", 0.0) + ms + log.info("Warmup complete: %d variant(s) in %.0f ms", len(self.warm_variants), ms) + return {"ms": ms, "variants": list(self.warm_variants)} + + # ---- inference ------------------------------------------------------------------------------------------- + @classmethod + def validate_params(cls, params: Optional[Mapping[str, Any]]) -> Dict[str, Any]: + """Per-request knobs -> typed values with defaults. Unknown names, values outside ``[min, max]`` (either + bound may be None), non-booleans for ``bool``, and booleans or non-integral numbers for ``int`` raise + ``InputError``; numeric strings are accepted for numbers. ``None`` is accepted for a param whose default + is ``None`` (it means "not set"), so ``validate_params(validate_params(p)) == validate_params(p)``.""" + out = {k: spec[3] for k, spec in cls.RUNTIME_PARAMS.items()} + for k, v in (params or {}).items(): + if k not in cls.RUNTIME_PARAMS: + raise tio.InputError(f"unknown parameter {k!r}; allowed: {sorted(cls.RUNTIME_PARAMS)}") + typ, lo, hi, default = cls.RUNTIME_PARAMS[k] + if v is None and default is None: # "not set" (JSON null) = the default, so validation is idempotent: + out[k] = None # the server validates, then model(**params) validates again + continue + if typ is bool and not isinstance(v, bool): + raise tio.InputError(f"parameter {k!r} must be a boolean") + if typ in (int, float) and isinstance(v, bool): + raise tio.InputError(f"parameter {k!r} must be {typ.__name__}, not a boolean") + try: + if typ is int and not isinstance(v, int): + number = float(v) + if not number.is_integer(): + raise ValueError(v) + v = int(number) + else: + v = typ(v) + except (TypeError, ValueError, OverflowError): + raise tio.InputError(f"parameter {k!r} must be {typ.__name__}") from None + if typ is float and not math.isfinite(v): + raise tio.InputError(f"parameter {k!r} must be finite") + if (lo is not None and v < lo) or (hi is not None and v > hi): + raise tio.InputError(f"parameter {k!r}={v} is outside [{lo}, {hi}]") + out[k] = v + return out + + def __call__(self, points: Any = None, *, sweeps: Optional[Sequence] = None, images: Any = None, + calibration: Optional[Mapping] = None, stream: Optional[Mapping] = None, + inputs: Any = None, **params: Any): + """One frame (batch 1). ``points``: path / bytes / (N, C) array / PointCloud / JSON envelope. + ``sweeps``: ``[{"points", "time_lag_s", "T_current_from_sweep"}]``. ``images``: list of camera dicts or + CameraImage. ``calibration``: dict (or ``{"preset": name}``, resolved by the server). ``stream``: + ``{"id", "reset", "timestamp_s", "T_world_from_ego"}``. ``inputs``: named arrays (planner; checked + against ``INPUT_SCHEMA`` when the class sets one). Keyword arguments named in ``EXTRA_INPUTS`` go to + ``_prepare``; the others are ``RUNTIME_PARAMS``. Returns the model's output object with ``timing_ms``.""" + self._check_open() + extra = {k: params.pop(k) for k in list(params) if k in self.EXTRA_INPUTS} + p = self.validate_params(params) + if inputs is not None and self.INPUT_SCHEMA is not None: + inputs = tio.load_named_arrays(inputs, self.INPUT_SCHEMA) + with self._lock: + self._check_open() # close() may have run while this call waited for the lock + t0 = time.perf_counter() + prepared = self._prepare(points=points, sweeps=sweeps, images=images, calibration=calibration, + stream=stream, inputs=inputs, **extra) + t1 = time.perf_counter() + raw = self._forward(prepared) + t2 = time.perf_counter() + out = self._postprocess(raw, prepared, p) + t3 = time.perf_counter() + out.timing_ms.update({"preprocess": (t1 - t0) * 1e3, "device": (t2 - t1) * 1e3, + "postprocess": (t3 - t2) * 1e3, "total": (t3 - t0) * 1e3}) + return out + + predict = __call__ + + # ---- lifetime -------------------------------------------------------------------------------------------- + def extra_info(self) -> Dict[str, Any]: + """Port-specific additions to :attr:`info` (knobs, precision policy, TraceRunner.describe() ...).""" + return {} + + @property + def info(self) -> Dict[str, Any]: + cls = type(self) + info = {"model": cls.MODEL_NAME, "variant": getattr(self, "variant", None), + "weights": getattr(self, "weights", None), "device": getattr(self, "device_info", None), + "warm_variants": getattr(self, "warm_variants", []), "warmup_ms": getattr(self, "warmup_ms", {}), + "compile_params": getattr(self, "compile_params", {}), "input_kind": cls.INPUT_KIND, + "point_fields": list(cls.POINT_FIELDS), "camera_order": list(cls.CAMERA_ORDER), + "labels": list(cls.LABELS), "runtime_params": {k: v[3] for k, v in cls.RUNTIME_PARAMS.items()}, + "extra_inputs": list(cls.EXTRA_INPUTS)} + if cls.INPUT_SCHEMA is not None: + info["input_schema"] = {name: {"shape": [None if d is None else int(d) for d in shape], + "dtype": np.dtype(dtype).name} + for name, (shape, dtype) in cls.INPUT_SCHEMA.items()} + if not getattr(self, "_closed", True): + info.update(self.extra_info()) + return info + + @property + def closed(self) -> bool: + return getattr(self, "_closed", True) + + def _check_open(self) -> None: + if self.closed: + raise RuntimeError(f"{type(self).__name__} is closed") + + def close(self) -> None: + """Release traces and device tensors; 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: + self._release() + finally: + dev = getattr(self, "device", None) + if dev is not None and self._owns_device: + close_device(dev) + self.device = None + + def __enter__(self) -> "ModelBase": + return self + + def __exit__(self, *exc: Any) -> None: + self.close() + + def __repr__(self) -> str: + state = ("closed" if self.closed + else f"{self.device_info.get('dispatch')} {self.device_info.get('grid')}") + return f"<{type(self).__name__} {self.MODEL_NAME} variant={getattr(self, 'variant', '?')} {state}>" + + # ---- port-specific hooks --------------------------------------------------------------------------------- + def _build(self) -> None: + """Load weights from ``self.weights_path``, convert them to device tensors, build the ttnn graph and its + ``TraceRunner`` (inputs, params, states, variants). No capture here.""" + raise NotImplementedError("port-specific: build the ttnn graph") + + def _warm_one(self, variant: Any) -> None: + """Warm up and capture the traces of one variant (``TraceRunner.capture``).""" + raise NotImplementedError("port-specific: compile + capture one variant") + + def _prepare(self, **kwargs: Any) -> Any: + """Host pre-processing ported from the Autoware node -> host buffers. Raise ``InputError`` for client + mistakes (missing input, wrong shape).""" + raise NotImplementedError("port-specific: host pre-processing") + + def _forward(self, prepared: Any) -> Any: + """Upload into the persistent device inputs, replay the matching trace, read the outputs.""" + raise NotImplementedError("port-specific: traced device forward") + + def _postprocess(self, raw: Any, prepared: Any, params: Dict[str, Any]) -> Any: + """Host post-processing ported from Autoware -> an output object of :mod:`ttaw.outputs`.""" + raise NotImplementedError("port-specific: host post-processing") + + def _release(self) -> None: + """Release traces and persistent device tensors (``TraceRunner.release()``). Also called when + ``from_pretrained`` fails half-way, so tolerate a partially built model (``getattr(self, "runner", None)``).""" diff --git a/code/tt_depthpro2/ttaw/decode.py b/code/tt_depthpro2/ttaw/decode.py new file mode 100644 index 0000000000000000000000000000000000000000..6b11c799629da67c74eb2bd6698814a84a5315df --- /dev/null +++ b/code/tt_depthpro2/ttaw/decode.py @@ -0,0 +1,424 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C16 decode: the dense CenterHead decoder of Autoware's lidar_centerpoint (also PointPainting's +image_projection_based_fusion), and the mapping of decoded boxes to Autoware ``DetectedObject`` fields. + +``decode_centerhead`` is ``generateBoxes3D_kernel`` + the ``is_score_keep`` compaction +(``autoware_lidar_centerpoint/lib/postprocess/postprocess_kernel.cu:52-178,220-226``), evaluated per BEV cell in +float32 as the kernel does (S:centerpoint:281-287): + +- ``score_c = sigmoid(heatmap[c])``; ``label`` = first class with the largest score (strict ``>`` scan); +- ``x = (voxel_x * ds) * (xi + reg[0]) + min_x``, ``y`` likewise with ``yi``: **no +0.5 cell offset**; +- the distance bin is the first ``i`` with ``sqrt(x^2 + y^2) < upper[i]``; beyond the last bin the cell is dropped; +- the cell is dropped when ``score < thresholds[bin][label]`` or ``sqrt(rot0^2 + rot1^2) < yaw_norm[label]``, and a + zero score is never kept; +- box: ``z = height[0]`` (box centre), ``width = exp(dim[0])``, ``length = exp(dim[1])``, ``height = exp(dim[2])`` + (the deployed ONNX regresses (w, l, h)), ``yaw = atan2(rot[0], rot[1])``, ``vel = vel[0:2]``. + +No max-pool peak finding and no top-K: every cell over threshold is a candidate, as in Autoware (S:centerpoint:310). +Thresholds outside [0, 1) are coerced to 0 (``centerpoint_config.hpp:79-93``): :meth:`CenterHeadDecodeConfig.create` +applies that. The decoder works on head maps from any source (ONNX Runtime, the torch reference, a device readback). + +Order: rows come out in cell order (``yi * W + xi``); :func:`sort_by_score` is the ``thrust::sort`` by descending +score, made deterministic (stable: ties keep the ascending cell order; thrust's sort is not stable). + +``decode_cells`` evaluates the same decoder at given cells and drops none: it keeps each cell's gate inputs +(distance bin, score threshold, yaw norm) and outcomes, so two head-map sources (device and fp32 reference) can be +compared at the same cells and every cell one keeps and the other drops can be explained. ``head_values_at`` stores +the maps at a set of cells (compact agreement goldens). + +``to_detected_objects`` is ``box3DToDetectedObject`` (``ros_utils.cpp:29-87``): the class name maps to an +``autoware_perception_msgs/ObjectClassification`` label (``getSemanticType``), ``yaw_ros = -yaw - pi/2`` (float), +dimensions (length, width, height), ``orientation_availability`` SIGN_UNKNOWN for car-like labels, and the twist in +the object frame when ``has_twist``. + +numpy only; no side effects on import. +""" +from __future__ import annotations + +import math +from dataclasses import dataclass, field, fields, replace +from typing import Any, Dict, List, Mapping, Optional, Sequence + +import numpy as np + +__all__ = [ + "AUTOWARE_LABELS", + "LABEL_IDS", + "SIGN_UNKNOWN", + "UNAVAILABLE", + "semantic_label", + "is_car_like", + "CenterHeadDecodeConfig", + "DecodedBoxes", + "sigmoid_f32", + "decode_centerhead", + "sort_by_score", + "head_values_at", + "DecodedCells", + "decode_cells", + "DetectedObjects", + "to_detected_objects", +] + +# autoware_perception_msgs/msg/ObjectClassification.msg label values (S:centerpoint:290) +AUTOWARE_LABELS = ("UNKNOWN", "CAR", "TRUCK", "BUS", "TRAILER", "MOTORCYCLE", "BICYCLE", "PEDESTRIAN") +LABEL_IDS = {name: i for i, name in enumerate(AUTOWARE_LABELS)} +# autoware_perception_msgs/msg/DetectedObjectKinematics.msg orientation_availability +UNAVAILABLE, SIGN_UNKNOWN = 0, 1 + +_SEMANTIC = {"CAR": "CAR", "TRUCK": "TRUCK", "BUS": "BUS", "TRAILER": "TRAILER", "BICYCLE": "BICYCLE", + "MOTORBIKE": "MOTORCYCLE", "PEDESTRIAN": "PEDESTRIAN"} + + +def semantic_label(class_name: str) -> int: + """``getSemanticType`` (``ros_utils.cpp:89-108``): network class name -> ObjectClassification label; MOTORBIKE -> + MOTORCYCLE; anything else -> UNKNOWN.""" + return LABEL_IDS[_SEMANTIC.get(class_name, "UNKNOWN")] + + +def is_car_like(label: Any) -> Any: + """``object_recognition_utils::isCarLikeVehicle``: CAR, TRUCK, BUS, TRAILER.""" + lab = np.asarray(label) + return np.isin(lab, [LABEL_IDS["CAR"], LABEL_IDS["TRUCK"], LABEL_IDS["BUS"], LABEL_IDS["TRAILER"]]) + + +def _coerce01(values: Any) -> np.ndarray: + v = np.asarray(values, dtype=np.float32) + return np.where((v >= 0.0) & (v < 1.0), v, np.float32(0.0)).astype(np.float32) + + +@dataclass(frozen=True) +class CenterHeadDecodeConfig: + """Decoder parameters. ``score_thresholds`` is (num_bins, num_classes), the node's ``[bin][class]`` layout + (``node.cpp:129-167``; read as ``thresholds[bin * C + label]``, ``postprocess_kernel.cu:114``).""" + + class_names: tuple + voxel_size_xy: tuple + range_min_xy: tuple + downsample_factor: int + distance_bin_upper_limits: tuple + score_thresholds: np.ndarray + yaw_norm_thresholds: np.ndarray + has_variance: bool = False + has_twist: bool = False + + @classmethod + def create(cls, *, class_names: Sequence[str], voxel_size_xy: Sequence[float], range_min_xy: Sequence[float], + downsample_factor: int, distance_bin_upper_limits: Sequence[float], score_thresholds: Any, + yaw_norm_thresholds: Sequence[float], has_variance: bool = False, + has_twist: bool = False) -> "CenterHeadDecodeConfig": + """Validated config with Autoware's coercions: thresholds outside [0, 1) -> 0, ascending bin limits, one + yaw-norm threshold per class. ``score_thresholds`` may be a scalar, a per-class list, or (bins, classes).""" + names = tuple(class_names) + bins = tuple(float(v) for v in distance_bin_upper_limits) + if list(bins) != sorted(bins): + raise ValueError("distance_bin_upper_limits must be ascending (centerpoint_config.hpp:67-70)") + thr = np.asarray(score_thresholds, dtype=np.float32) + if thr.ndim == 0: + thr = np.full((len(bins), len(names)), thr, np.float32) + elif thr.ndim == 1 and thr.shape[0] == len(names): + thr = np.tile(thr[None, :], (len(bins), 1)) + if thr.shape != (len(bins), len(names)): + raise ValueError(f"score_thresholds must be (bins={len(bins)}, classes={len(names)}), got {thr.shape}") + yaw = np.asarray(yaw_norm_thresholds, dtype=np.float64) + if yaw.shape != (len(names),): + raise ValueError("yaw_norm_thresholds needs one value per class (node.cpp:82-85)") + return cls(names, tuple(float(v) for v in voxel_size_xy), tuple(float(v) for v in range_min_xy), + int(downsample_factor), bins, _coerce01(thr), _coerce01(yaw), bool(has_variance), bool(has_twist)) + + def with_score_threshold(self, value: Optional[float]) -> "CenterHeadDecodeConfig": + """The same config with every class / bin threshold set to ``value`` (coerced like Autoware); None keeps it.""" + if value is None: + return self + return replace(self, score_thresholds=_coerce01(np.full_like(self.score_thresholds, value))) + + @property + def num_classes(self) -> int: + return len(self.class_names) + + +@dataclass +class DecodedBoxes: + """Decoded candidates (struct of arrays, all of length N). ``yaw`` is the network ("mmdet3d") yaw.""" + + cell: np.ndarray # int64 cell index yi * W + xi + label: np.ndarray # int32 class index into class_names + score: np.ndarray # float32 max sigmoid + x: np.ndarray # float32 box centre, model frame + y: np.ndarray + z: np.ndarray + length: np.ndarray # float32 exp(dim[1]) + width: np.ndarray # float32 exp(dim[0]) + height: np.ndarray # float32 exp(dim[2]) + yaw: np.ndarray # float32 atan2(rot0, rot1) + vel_x: np.ndarray + vel_y: np.ndarray + + def __len__(self) -> int: + return int(self.score.shape[0]) + + def take(self, idx: Any) -> "DecodedBoxes": + idx = np.asarray(idx, dtype=np.int64) + return DecodedBoxes(**{f.name: getattr(self, f.name)[idx] for f in fields(self)}) + + def to_dict(self) -> Dict[str, np.ndarray]: + return {f.name: getattr(self, f.name) for f in fields(self)} + + +def sigmoid_f32(x: Any) -> np.ndarray: + """``1.0f / (1.0f + expf(-x))`` in float32 (``postprocess_kernel.cu:46-49``).""" + v = np.asarray(x, dtype=np.float32) + with np.errstate(over="ignore"): + return (np.float32(1.0) / (np.float32(1.0) + np.exp(-v))).astype(np.float32) + + +def decode_centerhead(heads: Mapping[str, Any], cfg: CenterHeadDecodeConfig) -> DecodedBoxes: + """Decode the six head maps ``heatmap (C, H, W)``, ``reg (2, H, W)``, ``height (1, H, W)``, ``dim (3, H, W)``, + ``rot (2, H, W)``, ``vel (2, H, W)`` (a leading batch axis of 1 is accepted) -> candidates in cell order.""" + if cfg.has_variance: + raise NotImplementedError("variance heads (CenterPoint-sigma) are not supported by this decoder") + + def get(name: str, channels: int) -> np.ndarray: + a = np.asarray(heads[name], dtype=np.float32) + if a.ndim == 4: + if a.shape[0] != 1: + raise ValueError(f"{name}: batch {a.shape[0]} != 1") + a = a[0] + if a.ndim != 3 or a.shape[0] < channels: + raise ValueError(f"{name}: expected ({channels}, H, W), got {a.shape}") + return a + + hm = get("heatmap", cfg.num_classes)[:cfg.num_classes] + C, H, W = hm.shape + reg, hei, dim, rot = get("reg", 2), get("height", 1), get("dim", 3), get("rot", 2) + vel = get("vel", 2) if "vel" in heads else np.zeros((2, H, W), np.float32) + for name, a in (("reg", reg), ("height", hei), ("dim", dim), ("rot", rot), ("vel", vel)): + if a.shape[1:] != (H, W): + raise ValueError(f"{name} is {a.shape[1:]}, heatmap is {(H, W)}") + scores = sigmoid_f32(hm) + nan = np.isnan(scores) + if nan.any(): # NaN never wins the strict '>' scan; an all-NaN cell keeps label -1 and score 0 + scores = np.where(nan, np.float32(-np.inf), scores) + label = np.argmax(scores, axis=0).astype(np.int32) # first max == strict '>' from -1 + max_score = np.take_along_axis(scores, label[None].astype(np.int64), 0)[0] + found = np.isfinite(max_score) + max_score = np.where(found, max_score, np.float32(0.0)).astype(np.float32) + yi, xi = np.meshgrid(np.arange(H, dtype=np.float32), np.arange(W, dtype=np.float32), indexing="ij") + f32 = np.float32 + sx = f32(f32(cfg.voxel_size_xy[0]) * f32(cfg.downsample_factor)) + sy = f32(f32(cfg.voxel_size_xy[1]) * f32(cfg.downsample_factor)) + x = (sx * (xi + reg[0]) + f32(cfg.range_min_xy[0])).astype(np.float32) + y = (sy * (yi + reg[1]) + f32(cfg.range_min_xy[1])).astype(np.float32) + radial = np.sqrt(x * x + y * y).astype(np.float32) + bucket = np.full((H, W), -1, dtype=np.int64) + for i in range(len(cfg.distance_bin_upper_limits) - 1, -1, -1): # first upper limit above the distance + bucket = np.where(radial < f32(cfg.distance_bin_upper_limits[i]), i, bucket) + thr = cfg.score_thresholds[np.clip(bucket, 0, None), np.clip(label, 0, None)] + yaw_norm = np.sqrt(rot[0] * rot[0] + rot[1] * rot[1]).astype(np.float32) + yaw_thr = cfg.yaw_norm_thresholds[np.clip(label, 0, None)] + keep = found & (bucket >= 0) & ~(max_score < thr) & (yaw_norm >= yaw_thr) & (max_score > 0.0) + cell = np.nonzero(keep.ravel())[0] + + def at(a: np.ndarray) -> np.ndarray: + return a.reshape(-1)[cell] + + return DecodedBoxes( + cell=cell.astype(np.int64), label=at(label).astype(np.int32), score=at(max_score), x=at(x), y=at(y), + z=at(hei[0]), length=np.exp(at(dim[1])).astype(np.float32), width=np.exp(at(dim[0])).astype(np.float32), + height=np.exp(at(dim[2])).astype(np.float32), yaw=np.arctan2(at(rot[0]), at(rot[1])).astype(np.float32), + vel_x=at(vel[0]), vel_y=at(vel[1])) + + +def sort_by_score(boxes: DecodedBoxes) -> DecodedBoxes: + """Descending score, stable (ties keep cell order): a deterministic ``thrust::sort(..., score_greater())``.""" + return boxes.take(np.argsort(-boxes.score, kind="stable")) + + +# ------------------------------------------------------------------ the decoder at given cells (agreement metrics) + +def head_values_at(heads: Mapping[str, Any], cells: Any) -> Dict[str, np.ndarray]: + """The channels of every head map ``(C, H, W)`` (a leading batch axis of 1 is accepted) at the BEV cells + ``cells`` (``yi * W + xi``, any order) -> ``{name: (C, K) float32}``: an exact, compact form of the maps at the + cells that matter (agreement goldens). :func:`decode_cells` decodes it.""" + idx = np.asarray(cells, dtype=np.int64).reshape(-1) + out: Dict[str, np.ndarray] = {} + for name, a in heads.items(): + a = np.asarray(a, dtype=np.float32) + if a.ndim == 4: + if a.shape[0] != 1: + raise ValueError(f"{name}: batch {a.shape[0]} != 1") + a = a[0] + if a.ndim != 3: + raise ValueError(f"{name}: expected (C, H, W), got {a.shape}") + flat = a.reshape(a.shape[0], -1) + if idx.size and (idx.min() < 0 or idx.max() >= flat.shape[1]): + raise IndexError(f"{name}: cells outside [0, {flat.shape[1]})") + out[name] = np.ascontiguousarray(flat[:, idx]) + return out + + +@dataclass +class DecodedCells: + """:func:`decode_centerhead` evaluated at given cells with **no cell dropped** (struct of arrays, length K). The + box fields are those of :class:`DecodedBoxes`, bit-identical to ``decode_centerhead``'s row for every cell it + keeps (``keep``); the gate inputs and outcomes are kept per cell, so a cell one implementation keeps and another + drops can be explained (score threshold vs yaw-norm gate).""" + + cell: np.ndarray # int64 cell index yi * W + xi + label: np.ndarray # int32 first-max class; -1 when every class score is NaN + score: np.ndarray # float32 max sigmoid (0 when every class score is NaN) + x: np.ndarray + y: np.ndarray + z: np.ndarray + length: np.ndarray + width: np.ndarray + height: np.ndarray + yaw: np.ndarray # float32 network yaw atan2(rot0, rot1) + vel_x: np.ndarray + vel_y: np.ndarray + yaw_norm: np.ndarray # float32 sqrt(rot0^2 + rot1^2): the input of the yaw-norm gate + distance_bin: np.ndarray # int64 first bin with radial distance < its upper limit; -1 beyond the last + score_threshold: np.ndarray # float32 thresholds[bin][label] (bin and label clipped to 0, as the decoder) + yaw_norm_threshold: np.ndarray # float32 yaw-norm threshold of the label + passes_score: np.ndarray # bool: a label, inside a bin, not (score < threshold), score > 0 + passes_yaw_norm: np.ndarray # bool: yaw_norm >= the label's yaw-norm threshold + + @property + def keep(self) -> np.ndarray: + """The cells ``decode_centerhead`` keeps (both gates pass).""" + return self.passes_score & self.passes_yaw_norm + + def __len__(self) -> int: + return int(self.score.shape[0]) + + def take(self, idx: Any) -> "DecodedCells": + idx = np.asarray(idx, dtype=np.int64) + return DecodedCells(**{f.name: getattr(self, f.name)[idx] for f in fields(self)}) + + def to_boxes(self) -> DecodedBoxes: + """The :class:`DecodedBoxes` fields of every cell (gates not applied: ``.take(np.nonzero(keep)[0])`` first + for the decoder's rows).""" + return DecodedBoxes(**{f.name: getattr(self, f.name) for f in fields(DecodedBoxes)}) + + +def decode_cells(values: Mapping[str, Any], cells: Any, grid_w: int, cfg: CenterHeadDecodeConfig) -> DecodedCells: + """The decoder at the cells ``cells`` of a head grid ``grid_w`` cells wide, from their channel values ``values`` + (``{name: (C, K)}``, :func:`head_values_at`; ``vel`` optional), in the float32 arithmetic of + :func:`decode_centerhead` and with the gate outcomes instead of the drop (:class:`DecodedCells`).""" + if cfg.has_variance: + raise NotImplementedError("variance heads (CenterPoint-sigma) are not supported by this decoder") + idx = np.asarray(cells, dtype=np.int64).reshape(-1) + k = idx.size + + def get(name: str, channels: int) -> np.ndarray: + a = np.asarray(values[name], dtype=np.float32) + if a.ndim != 2 or a.shape[0] < channels or a.shape[1] != k: + raise ValueError(f"{name}: expected ({channels}, {k}), got {a.shape}") + return a + + hm = get("heatmap", cfg.num_classes)[:cfg.num_classes] + reg, hei, dim, rot = get("reg", 2), get("height", 1), get("dim", 3), get("rot", 2) + vel = get("vel", 2) if "vel" in values else np.zeros((2, k), np.float32) + scores = sigmoid_f32(hm) + nan = np.isnan(scores) + if nan.any(): + scores = np.where(nan, np.float32(-np.inf), scores) + label = np.argmax(scores, axis=0).astype(np.int32) if k else np.zeros(0, np.int32) + max_score = np.take_along_axis(scores, label[None].astype(np.int64), 0)[0] if k else np.zeros(0, np.float32) + found = np.isfinite(max_score) + max_score = np.where(found, max_score, np.float32(0.0)).astype(np.float32) + f32 = np.float32 + w = int(grid_w) + yi, xi = (idx // w).astype(np.float32), (idx % w).astype(np.float32) + sx = f32(f32(cfg.voxel_size_xy[0]) * f32(cfg.downsample_factor)) + sy = f32(f32(cfg.voxel_size_xy[1]) * f32(cfg.downsample_factor)) + x = (sx * (xi + reg[0]) + f32(cfg.range_min_xy[0])).astype(np.float32) + y = (sy * (yi + reg[1]) + f32(cfg.range_min_xy[1])).astype(np.float32) + radial = np.sqrt(x * x + y * y).astype(np.float32) + bucket = np.full(k, -1, dtype=np.int64) + for i in range(len(cfg.distance_bin_upper_limits) - 1, -1, -1): + bucket = np.where(radial < f32(cfg.distance_bin_upper_limits[i]), i, bucket) + thr = cfg.score_thresholds[np.clip(bucket, 0, None), np.clip(label, 0, None)].astype(np.float32) + yaw_norm = np.sqrt(rot[0] * rot[0] + rot[1] * rot[1]).astype(np.float32) + yaw_thr = cfg.yaw_norm_thresholds[np.clip(label, 0, None)].astype(np.float32) + return DecodedCells( + cell=idx.copy(), label=np.where(found, label, -1).astype(np.int32), score=max_score, x=x, y=y, + z=hei[0].copy(), length=np.exp(dim[1]).astype(np.float32), width=np.exp(dim[0]).astype(np.float32), + height=np.exp(dim[2]).astype(np.float32), yaw=np.arctan2(rot[0], rot[1]).astype(np.float32), + vel_x=vel[0].copy(), vel_y=vel[1].copy(), yaw_norm=yaw_norm, distance_bin=bucket, score_threshold=thr, + yaw_norm_threshold=yaw_thr, passes_score=found & (bucket >= 0) & ~(max_score < thr) & (max_score > 0.0), + passes_yaw_norm=yaw_norm >= yaw_thr) + + +@dataclass +class DetectedObjects: + """Autoware ``DetectedObject`` fields of N objects (struct of arrays). Positions and dimensions hold the float32 + values of the decoder (the message stores them as double); ``yaw`` is the ROS yaw (float32 arithmetic).""" + + label: np.ndarray # uint8 ObjectClassification label + existence_probability: np.ndarray # float32 + x: np.ndarray + y: np.ndarray + z: np.ndarray + yaw: np.ndarray + length: np.ndarray + width: np.ndarray + height: np.ndarray + orientation_availability: np.ndarray # uint8: SIGN_UNKNOWN for car-like labels, else UNAVAILABLE + twist_x: Optional[np.ndarray] = None # object-frame twist (has_twist only) + twist_y: Optional[np.ndarray] = None + source_index: Optional[np.ndarray] = None # row of the DecodedBoxes each object came from + label_before_remap: Optional[np.ndarray] = None + extra: Dict[str, np.ndarray] = field(default_factory=dict) + + def __len__(self) -> int: + return int(self.existence_probability.shape[0]) + + def take(self, idx: Any) -> "DetectedObjects": + idx = np.asarray(idx, dtype=np.int64) + out = {} + for f in fields(self): + v = getattr(self, f.name) + if f.name == "extra": + out[f.name] = {k: a[idx] for k, a in v.items()} + else: + out[f.name] = None if v is None else v[idx] + return DetectedObjects(**out) + + def boxes_xyzlwh_yaw(self) -> np.ndarray: + """(N, 7) float32 x, y, z, length, width, height, yaw (the ``ttaw.outputs.Detections3D`` layout).""" + return np.stack([self.x, self.y, self.z, self.length, self.width, self.height, self.yaw], + axis=1).astype(np.float32) + + def to_records(self, labels: Sequence[str] = AUTOWARE_LABELS) -> List[Dict[str, Any]]: + out = [] + for i in range(len(self)): + d = {"label": labels[int(self.label[i])], "existence_probability": float(self.existence_probability[i]), + "x": float(self.x[i]), "y": float(self.y[i]), "z": float(self.z[i]), "yaw": float(self.yaw[i]), + "length": float(self.length[i]), "width": float(self.width[i]), "height": float(self.height[i]), + "orientation_availability": int(self.orientation_availability[i])} + if self.label_before_remap is not None and self.label_before_remap[i] != self.label[i]: + d["label_before_remap"] = labels[int(self.label_before_remap[i])] + out.append(d) + return out + + +def to_detected_objects(boxes: DecodedBoxes, class_names: Sequence[str], *, has_twist: bool = False) -> DetectedObjects: + """``box3DToDetectedObject`` for every row (module docstring).""" + table = np.array([semantic_label(n) for n in class_names], dtype=np.uint8) + lab = np.asarray(boxes.label, dtype=np.int64) + valid = (lab >= 0) & (lab < len(class_names)) + label = np.where(valid, table[np.clip(lab, 0, len(class_names) - 1)], LABEL_IDS["UNKNOWN"]).astype(np.uint8) + yaw = (-np.asarray(boxes.yaw, dtype=np.float32).astype(np.float64) - math.pi / 2.0).astype(np.float32) + orient = np.where(is_car_like(label), SIGN_UNKNOWN, UNAVAILABLE).astype(np.uint8) + tx = ty = None + if has_twist: + c, s = np.cos(yaw), np.sin(yaw) # float32, as std::cos(float) + tx = (c * boxes.vel_x + s * boxes.vel_y).astype(np.float32) + ty = (-s * boxes.vel_x + c * boxes.vel_y).astype(np.float32) + return DetectedObjects(label=label, existence_probability=np.asarray(boxes.score, np.float32), + x=boxes.x.copy(), y=boxes.y.copy(), z=boxes.z.copy(), yaw=yaw, + length=boxes.length.copy(), width=boxes.width.copy(), height=boxes.height.copy(), + orientation_availability=orient, twist_x=tx, twist_y=ty, + source_index=np.arange(len(boxes), dtype=np.int64), label_before_remap=label.copy(), + extra={"cell": np.asarray(boxes.cell, dtype=np.int64)}) diff --git a/code/tt_depthpro2/ttaw/device.py b/code/tt_depthpro2/ttaw/device.py new file mode 100644 index 0000000000000000000000000000000000000000..dab64c52acf24581e6276bfcb67dbf18d6da33d2 --- /dev/null +++ b/code/tt_depthpro2/ttaw/device.py @@ -0,0 +1,339 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C01: open the Blackhole p150 the way every published number is measured. + +Default: dispatch on the idle Ethernet cores (``ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH)``), which frees the +Tensix dispatch column and gives a 12x10 = 120-core compute grid on a p150b (11x10 with stock WORKER dispatch). ETH +dispatch needs ``patches/tt-metal-eth-dispatch.patch`` on tt-metal 44d6650; the patch adds the marker +``single_chip_arch_1cq_no_dispatch_s`` to ``tt_metal/impl/dispatch/topology.cpp``, which ``dispatch="auto"`` looks +for. If the ETH open fails, a ``RuntimeWarning`` is issued and WORKER dispatch is used (``allow_fallback=False`` +raises instead, for the container smoke). Never hard-code the grid: use :func:`compute_grid` / +``device.compute_with_storage_grid_size()``. + +``ttnn`` is imported inside the functions, so importing this module has no side effects. + +Example:: + + from .ttaw.device import device_session, describe_device + + with device_session(dispatch="eth", num_command_queues=2, trace_region_size=64 << 20) as dev: + print(describe_device(dev)) # {'dispatch': 'eth', 'grid': '12x10', 'cores': 120, 'num_command_queues': 2, ...} +""" +from __future__ import annotations + +import contextlib +import importlib.util +import os +import warnings +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any, Dict, Iterator, Mapping, Optional, Tuple + +__all__ = [ + "DISPATCH_MODES", + "PATCH_MARKER", + "DEFAULT_L1_SMALL_SIZE", + "DEFAULT_TRACE_REGION_SIZE", + "P150_ETH_GRID", + "DeviceConfig", + "tt_metal_home", + "eth_dispatch_patch_present", + "reshape_patch_present", + "RESHAPE_PATCH_MARKER", + "resolve_dispatch", + "open_device", + "describe_device", + "open_info", + "close_device", + "device_session", + "compute_grid", + "core_grid", + "full_core_range_set", +] + +DISPATCH_MODES = ("eth", "worker", "auto") +PATCH_MARKER = "single_chip_arch_1cq_no_dispatch_s" +PATCH_RELPATH = Path("tt_metal", "impl", "dispatch", "topology.cpp") +DEFAULT_L1_SMALL_SIZE = 32768 # conv / pool config tensors (CNN demos use 24576-32768) +DEFAULT_TRACE_REGION_SIZE = 64 << 20 # DRAM bytes for the trace command buffers of all captured traces +P150_ETH_GRID = (12, 10) # p150b compute grid with ETH dispatch (research/DISPATCH.md) + +# id(device) -> (device, what open_device actually did: dispatch used, CQs, sizes); read by describe_device. The +# device itself is kept so that its id cannot be reused by another object while the entry exists (a device opened +# outside ttaw must never inherit a dead device's record); close_device removes the entry. +_OPEN_INFO: Dict[int, Tuple[Any, Dict[str, Any]]] = {} +# id(device) -> device for every device closed by close_device: a second close is a no-op. The reference keeps the +# closed object alive, so its id cannot be reused by a later device (ttnn device objects take no attributes). +_CLOSED: Dict[int, Any] = {} + + +def _normalize_dispatch(dispatch: Optional[str]) -> str: + mode = (dispatch or "eth").strip().lower() + if mode not in DISPATCH_MODES: + raise ValueError(f"dispatch={dispatch!r}: expected one of {DISPATCH_MODES}") + return mode + + +@dataclass(frozen=True) +class DeviceConfig: + """Everything :func:`open_device` needs, so a model can pin it, log it and A/B it from the environment.""" + + device_id: int = 0 + dispatch: str = "eth" + num_command_queues: int = 1 + l1_small_size: int = DEFAULT_L1_SMALL_SIZE + trace_region_size: int = DEFAULT_TRACE_REGION_SIZE + worker_l1_size: Optional[int] = None + allow_fallback: bool = True + + def __post_init__(self) -> None: + object.__setattr__(self, "dispatch", _normalize_dispatch(self.dispatch)) + if self.num_command_queues not in (1, 2): + raise ValueError(f"num_command_queues={self.num_command_queues}: expected 1 or 2") + if self.l1_small_size < 0 or self.trace_region_size < 0: + raise ValueError("l1_small_size and trace_region_size must be >= 0") + if self.worker_l1_size is not None and self.worker_l1_size <= 0: + raise ValueError("worker_l1_size must be a positive byte count (or None for tt-metal's default)") + + @classmethod + def from_env(cls, prefix: str, env: Optional[Mapping[str, str]] = None, **defaults: Any) -> "DeviceConfig": + """Model defaults overridden by ``_DISPATCH`` (eth|worker|auto), ``_NUM_CQS``, + ``_L1_SMALL``, ``_TRACE_REGION``, ``_WORKER_L1_SIZE`` and ``TT_DEVICE_ID`` + (BUNDLE_CONVENTIONS.md section 7.6). Empty or ``0`` values keep the default. Read once, at build.""" + env = os.environ if env is None else env + values = dict(defaults) + + def _int(name: str) -> Optional[int]: + raw = (env.get(name) or "").strip() + if not raw: + return None + try: + value = int(float(raw)) + except ValueError: + raise ValueError(f"{name}={raw!r} is not an integer") from None + return value or None + + dispatch = (env.get(f"{prefix}_DISPATCH") or "").strip() + if dispatch: + values["dispatch"] = dispatch + for key, name in (("num_command_queues", f"{prefix}_NUM_CQS"), ("l1_small_size", f"{prefix}_L1_SMALL"), + ("trace_region_size", f"{prefix}_TRACE_REGION"), + ("worker_l1_size", f"{prefix}_WORKER_L1_SIZE")): + value = _int(name) + if value is not None: + values[key] = value + device_id = (env.get("TT_DEVICE_ID") or "").strip() + if device_id: + values["device_id"] = int(device_id) + return cls(**values) + + def open(self): + """``open_device(**self)``.""" + return open_device(**asdict(self)) + + +def tt_metal_home() -> Optional[Path]: + """The tt-metal tree: ``$TT_METAL_HOME``, else ``$TT_METAL_RUNTIME_ROOT``, else the tree holding the ``ttnn`` + package (located with ``importlib.util.find_spec``, so ttnn is not imported).""" + for var in ("TT_METAL_HOME", "TT_METAL_RUNTIME_ROOT"): + value = os.environ.get(var) + if value and Path(value).is_dir(): + return Path(value) + try: + spec = importlib.util.find_spec("ttnn") + except (ImportError, ValueError): + spec = None + if spec is None or not spec.origin: + return None + for parent in Path(spec.origin).resolve().parents: + if (parent / "tt_metal").is_dir(): + return parent + return None + + +def eth_dispatch_patch_present(home: Optional[os.PathLike] = None) -> bool: + """True when the tt-metal tree carries the ETH-dispatch patch (its marker string is in ``topology.cpp``).""" + root = tt_metal_home() if home is None else Path(home) + if root is None: + return False + try: + return PATCH_MARKER in (Path(root) / PATCH_RELPATH).read_text(errors="ignore") + except OSError: + return False + + +# patches/tt-metal-reshape-rm-sys1419.patch (ttaw 0.23.2): single-kernel ROW_MAJOR reshape for small Blackhole DRAM +# destination pages (SYS-1419: the dual-kernel path hangs the chip under ETH dispatch; logs/meteor/hangfix/) +RESHAPE_PATCH_MARKER = "dual_kernel_min_dram_dest_page_bytes" +RESHAPE_PATCH_RELPATH = "ttnn/cpp/ttnn/operations/data_movement/reshape_view/device/reshape_rm_program_factory.cpp" +RESHAPE_PATCH_ENV = "TT_METAL_RESHAPE_RM_DUAL_DRAM_MIN_PAGE_BYTES" + + +def reshape_patch_present(home: Optional[os.PathLike] = None, *, min_page_bytes: int = 4096) -> bool: + """True when the tt-metal tree carries the reshape patch (marker in ``reshape_rm_program_factory.cpp``) and its + runtime override (``TT_METAL_RESHAPE_RM_DUAL_DRAM_MIN_PAGE_BYTES``) does not lower the guard below + ``min_page_bytes``. Like :func:`eth_dispatch_patch_present` it reads the source tree: the library must have been + rebuilt from it (the container image always is).""" + raw = (os.environ.get(RESHAPE_PATCH_ENV) or "").strip() + if raw: + try: + if int(raw) < int(min_page_bytes): + return False + except ValueError: + return False + root = tt_metal_home() if home is None else Path(home) + if root is None: + return False + try: + return RESHAPE_PATCH_MARKER in (Path(root) / RESHAPE_PATCH_RELPATH).read_text(errors="ignore") + except OSError: + return False + + +def resolve_dispatch(dispatch: str = "auto", *, home: Optional[os.PathLike] = None) -> str: + """``"eth"`` / ``"worker"`` pass through; ``"auto"`` becomes ``"eth"`` when the patch marker is found, else + ``"worker"`` with a ``RuntimeWarning`` (the grid is then 11x10 and the published numbers do not apply).""" + mode = _normalize_dispatch(dispatch) + if mode != "auto": + return mode + if eth_dispatch_patch_present(home): + return "eth" + warnings.warn( + "the tt-metal ETH-dispatch patch was not found (marker " + f"{PATCH_MARKER!r} missing from {PATCH_RELPATH} under {tt_metal_home()}); using WORKER dispatch: the compute " + "grid is 11x10 on a p150 and the published numbers do not apply (apply patches/tt-metal-eth-dispatch.patch)", + RuntimeWarning, stacklevel=3) + return "worker" + + +def open_device(device_id: int = 0, *, dispatch: str = "eth", num_command_queues: int = 1, + l1_small_size: int = DEFAULT_L1_SMALL_SIZE, trace_region_size: int = DEFAULT_TRACE_REGION_SIZE, + worker_l1_size: Optional[int] = None, allow_fallback: bool = True): + """Open one chip and return the ttnn (1x1 mesh) device. + + Args: + device_id: chip id as ttnn sees it. + dispatch: ``"eth"`` (default; 12x10 on a p150b), ``"worker"`` (A/B only; 11x10) or ``"auto"`` (ETH when the + patch marker is present, else WORKER with a ``RuntimeWarning``). + num_command_queues: 1, or 2 for trace + 2CQ (input upload on CQ1). + l1_small_size: L1_SMALL bytes per core (conv / pool config tensors). + trace_region_size: DRAM bytes reserved for trace buffers (0 = dynamic top-down buffers). + worker_l1_size: allocatable L1 per core in bytes; smaller values grow the kernel-config ring buffer + (TT_PLATFORM.md section 1). ``None`` keeps tt-metal's default. + allow_fallback: when the ETH open fails, warn and open with WORKER dispatch (``True``) or re-raise. + """ + import ttnn + + cfg = DeviceConfig(device_id=device_id, dispatch=dispatch, num_command_queues=num_command_queues, + l1_small_size=l1_small_size, trace_region_size=trace_region_size, + worker_l1_size=worker_l1_size, allow_fallback=allow_fallback) + mode = resolve_dispatch(cfg.dispatch) + params: Dict[str, Any] = dict(l1_small_size=cfg.l1_small_size, trace_region_size=cfg.trace_region_size, + num_command_queues=cfg.num_command_queues) + if cfg.worker_l1_size is not None: + params["worker_l1_size"] = cfg.worker_l1_size + device = None + fallback: Optional[str] = None + if mode == "eth": + try: + device = ttnn.open_device(device_id=cfg.device_id, + dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), **params) + except Exception as exc: # noqa: BLE001 -- tt-metal without the ETH-dispatch patch, or no idle ETH cores + if not cfg.allow_fallback: + raise + fallback = f"{type(exc).__name__}: {exc}" + warnings.warn(f"ETH dispatch is not available ({fallback}); falling back to WORKER dispatch: the compute " + "grid is 11x10 on a p150 and the published numbers do not apply " + "(apply patches/tt-metal-eth-dispatch.patch)", RuntimeWarning, stacklevel=2) + mode = "worker" + if device is None: + device = ttnn.open_device(device_id=cfg.device_id, + dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.WORKER), **params) + _CLOSED.pop(id(device), None) + _OPEN_INFO[id(device)] = (device, { + "dispatch": mode, "dispatch_requested": cfg.dispatch, "fallback": fallback, "device_id": cfg.device_id, + "num_command_queues": cfg.num_command_queues, "l1_small_size": cfg.l1_small_size, + "trace_region_size": cfg.trace_region_size, "worker_l1_size": cfg.worker_l1_size, + }) + gx, gy = compute_grid(device) + if mode == "eth" and (gx, gy) != P150_ETH_GRID: + warnings.warn(f"compute grid is {gx}x{gy}, expected {P150_ETH_GRID[0]}x{P150_ETH_GRID[1]} with ETH dispatch " + "on a p150b", RuntimeWarning, stacklevel=2) + return device + + +def compute_grid(device) -> Tuple[int, int]: + """``(x, y)`` of ``device.compute_with_storage_grid_size()``: (12, 10) with ETH dispatch on a p150b.""" + g = device.compute_with_storage_grid_size() + return int(g.x), int(g.y) + + +def core_grid(device): + """``ttnn.CoreGrid`` covering the whole compute grid (for ``core_grid=`` / program configs).""" + import ttnn + + x, y = compute_grid(device) + return ttnn.CoreGrid(y=y, x=x) + + +def full_core_range_set(device): + """``ttnn.CoreRangeSet`` of one rectangle covering the whole compute grid (for ``generic_op`` descriptors).""" + import ttnn + + x, y = compute_grid(device) + return ttnn.CoreRangeSet([ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(x - 1, y - 1))]) + + +def open_info(device) -> Dict[str, Any]: + """What :func:`open_device` recorded for ``device`` (dispatch used, CQs, sizes), ``{}`` for a device opened + elsewhere.""" + entry = _OPEN_INFO.get(id(device)) + return dict(entry[1]) if entry is not None and entry[0] is device else {} + + +def _arch_name(device) -> str: + try: + arch = device.arch() + except Exception: # noqa: BLE001 -- a fake or partially closed device + return "unknown" + name = getattr(arch, "name", None) or str(arch).rsplit(".", 1)[-1] + return name.lower() + + +def describe_device(device, device_id: Optional[int] = None) -> Dict[str, Any]: + """What ``/info`` and ``model.info`` report: dispatch actually used, CQs, grid, cores, arch and open parameters. + + A device opened outside :func:`open_device` reports ``dispatch="unknown"``.""" + gx, gy = compute_grid(device) + info: Dict[str, Any] = {"dispatch": "unknown", "num_command_queues": None} + info.update(open_info(device)) + info.update({"grid": f"{gx}x{gy}", "grid_x": gx, "grid_y": gy, "cores": gx * gy, "arch": _arch_name(device), + "eth_patch": eth_dispatch_patch_present()}) + if device_id is not None: + info["device_id"] = device_id + return info + + +def close_device(device) -> None: + """Close a device (synchronizes first, as ``ttnn.close_device`` does). Idempotent: closing a device this + function already closed does nothing.""" + import ttnn + + if _CLOSED.get(id(device)) is device: + return + if open_info(device): + del _OPEN_INFO[id(device)] + try: + ttnn.close_device(device) + finally: + _CLOSED[id(device)] = device + + +@contextlib.contextmanager +def device_session(device_id: int = 0, **kwargs: Any) -> Iterator[Any]: + """``with device_session(dispatch="eth", num_command_queues=2) as dev:`` -- opens with :func:`open_device` + (same keyword arguments) and always closes, also when the body raises.""" + device = open_device(device_id, **kwargs) + try: + yield device + finally: + close_device(device) diff --git a/code/tt_depthpro2/ttaw/geometry.py b/code/tt_depthpro2/ttaw/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..bee2099f90087e7c1d6f04da5b9e41a3ca7e6ae7 --- /dev/null +++ b/code/tt_depthpro2/ttaw/geometry.py @@ -0,0 +1,194 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C10 geometry (sweep and ego-motion parts): rigid transforms in float64, Autoware's float32 sweep transform, and +the yaw / quaternion conventions of the LiDAR detectors. + +Naming: ``T_a_from_b`` maps points of frame ``b`` into frame ``a`` (4x4, metres, row-major, translation in the last +column), so ``p_a = T_a_from_b @ p_b`` and ``T_a_from_c = T_a_from_b @ T_b_from_c``. + +Two precisions on purpose: + +- **float64** for composing poses (``compose``, ``invert_rigid``): what tf2 does, and what every port uses unless its + Autoware node does otherwise (S:streampetr:386; S:pointpainting:212-215; S:bevformer:437). +- **float32 as Autoware's lidar_centerpoint does it**: the node casts each TF to ``Eigen::Affine3f``, inverts and + multiplies in float32 (``pointcloud_densification.cpp:47-51,82-86``; ``voxel_generator.cpp:63``) and the CUDA + kernel ``generateSweepPoints_kernel`` applies the float32 affine as ``m0*x + m4*y + m8*z + m12`` (column-major, + ``preprocess_kernel.cu:58-90``). :func:`invert_affine_f32` and :func:`transform_points_f32` reproduce that + arithmetic in numpy float32 without fused multiply-adds, so they agree with the GPU to the last bit except where + nvcc contracts a multiply-add (an FMA rounds once): a sub-micrometre difference, irrelevant to 0.32 m pillars. + +Yaw conventions (S:centerpoint:305-307): the deployed CenterPoint ONNX regresses the "mmdet3d" yaw; Autoware +publishes ``yaw_ros = -yaw_net - pi/2`` counter-clockwise from +x of ``base_link`` (``ros_utils.cpp:55-60``). + +numpy only; no side effects on import. +""" +from __future__ import annotations + +import math +from typing import Any, Sequence + +import numpy as np + +from .io import parse_transform + +__all__ = [ + "as_transform", + "compose", + "invert_rigid", + "invert_affine_f32", + "compose_f32", + "transform_points", + "transform_points_f32", + "rotation_from_rpy", + "transform_from_xyz_rpy", + "quaternion_wxyz_from_yaw", + "yaw_from_quaternion_wxyz", + "yaw_from_rotation", + "wrap_angle", + "mmdet_yaw_to_ros", + "ros_yaw_to_mmdet", +] + + +# ------------------------------------------------------------------------------------------------- transforms + +def as_transform(obj: Any, *, field: str = "transform") -> np.ndarray: + """Any spelling :func:`ttaw.io.parse_transform` accepts (4x4 / 3x4 array, ``{matrix}``, + ``{translation, rotation_wxyz | rotation_xyzw | rotation}``, ``{x, y, z, roll, pitch, yaw}``) -> a validated + (4, 4) float64 rigid transform. A malformed value raises :class:`ttaw.io.InputError`.""" + return parse_transform(obj, field=field) + + +def compose(*transforms: np.ndarray) -> np.ndarray: + """``T_0 @ T_1 @ ... @ T_n`` in float64 (``compose(T_a_from_b, T_b_from_c) == T_a_from_c``).""" + if not transforms: + return np.eye(4) + out = np.asarray(transforms[0], dtype=np.float64) + for t in transforms[1:]: + out = out @ np.asarray(t, dtype=np.float64) + return out + + +def invert_rigid(T: np.ndarray) -> np.ndarray: + """Exact inverse of a rigid transform in float64: ``[R^T, -R^T t]``.""" + T = np.asarray(T, dtype=np.float64) + out = np.eye(4) + r = T[:3, :3] + out[:3, :3] = r.T + out[:3, 3] = -(r.T @ T[:3, 3]) + return out + + +def invert_affine_f32(T: np.ndarray) -> np.ndarray: + """``Eigen::Affine3f::inverse()`` (TransformTraits ``Affine``) in float32: the 3x3 linear part inverted through + its cofactors and the column-0 determinant (Eigen's ``compute_inverse<..., 3>``), translation ``-L^-1 t``, + every operation rounded to float32. Used by the Autoware densification emulation + (``pointcloud_densification.cpp:84``).""" + m = np.asarray(T, dtype=np.float32) + a = m[:3, :3] + f = np.float32 + + def cofactor(i: int, j: int) -> np.float32: # Eigen cofactor_3x3 + i1, i2, j1, j2 = (i + 1) % 3, (i + 2) % 3, (j + 1) % 3, (j + 2) % 3 + return f(f(a[i1, j1] * a[i2, j2]) - f(a[i1, j2] * a[i2, j1])) + + det = f(f(cofactor(0, 0) * a[0, 0]) + f(cofactor(1, 0) * a[1, 0])) + f(cofactor(2, 0) * a[2, 0]) + if det == 0 or not np.isfinite(det): + raise ValueError("singular affine transform") + inv_det = f(f(1.0) / det) + inv = np.empty((3, 3), np.float32) + for i in range(3): + for j in range(3): + inv[i, j] = f(cofactor(j, i) * inv_det) # adjugate / det + out = np.eye(4, dtype=np.float32) + out[:3, :3] = inv + t = m[:3, 3] + for i in range(3): + out[i, 3] = -(f(f(inv[i, 0] * t[0]) + f(inv[i, 1] * t[1])) + f(inv[i, 2] * t[2])) + return out + + +def compose_f32(A: np.ndarray, B: np.ndarray) -> np.ndarray: + """``A @ B`` of two float32 affine matrices with float32 rounding after every product and sum, summed in index + order (Eigen's lazy product of two ``Affine3f``).""" + a = np.asarray(A, dtype=np.float32) + b = np.asarray(B, dtype=np.float32) + out = np.zeros((4, 4), np.float32) + for k in range(4): + out = (out + a[:, k:k + 1] * b[k:k + 1, :]).astype(np.float32) + return out + + +def transform_points(points: np.ndarray, T: np.ndarray) -> np.ndarray: + """``T @ [x, y, z, 1]`` for (N, >=3) points in float64 (extra columns are passed through unchanged).""" + p = np.asarray(points, dtype=np.float64) + T = np.asarray(T, dtype=np.float64) + out = p.copy() + out[:, :3] = p[:, :3] @ T[:3, :3].T + T[:3, 3] + return out + + +def transform_points_f32(xyz: np.ndarray, T: np.ndarray) -> np.ndarray: + """Autoware ``generateSweepPoints_kernel`` (``preprocess_kernel.cu:58-90``): the affine is cast to float32 and + each output coordinate is ``((m[r,0]*x + m[r,1]*y) + m[r,2]*z) + m[r,3]`` in float32, left to right (no FMA). + ``xyz``: (N, >=3); returns (N, 3) float32.""" + p = np.asarray(xyz, dtype=np.float32) + m = np.asarray(T, dtype=np.float32) + x, y, z = p[:, 0], p[:, 1], p[:, 2] + out = np.empty((len(p), 3), np.float32) + for r in range(3): + out[:, r] = ((m[r, 0] * x + m[r, 1] * y) + m[r, 2] * z) + m[r, 3] + return out + + +# ----------------------------------------------------------------------------------------------- rotations + +def rotation_from_rpy(roll: float, pitch: float, yaw: float) -> np.ndarray: + """tf2 ``setRPY``: ``R = Rz(yaw) @ Ry(pitch) @ Rx(roll)`` (float64).""" + cr, sr, cp, sp, cy, sy = (math.cos(roll), math.sin(roll), math.cos(pitch), math.sin(pitch), math.cos(yaw), + math.sin(yaw)) + return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr], + [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr], + [-sp, cp * sr, cp * cr]], dtype=np.float64) + + +def transform_from_xyz_rpy(x: float, y: float, z: float, roll: float = 0.0, pitch: float = 0.0, + yaw: float = 0.0) -> np.ndarray: + """A (4, 4) float64 transform from a translation and tf2 RPY angles (Autoware's calibration yaml spelling).""" + out = np.eye(4) + out[:3, :3] = rotation_from_rpy(roll, pitch, yaw) + out[:3, 3] = (x, y, z) + return out + + +def quaternion_wxyz_from_yaw(yaw: float) -> np.ndarray: + """``autoware_utils::create_quaternion_from_yaw``: rotation about +z, as (w, x, y, z) float64.""" + return np.array([math.cos(yaw / 2.0), 0.0, 0.0, math.sin(yaw / 2.0)], dtype=np.float64) + + +def yaw_from_quaternion_wxyz(q: Sequence[float]) -> float: + """``tf2::getYaw`` of a (w, x, y, z) quaternion.""" + w, x, y, z = (float(v) for v in q) + return math.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z)) + + +def yaw_from_rotation(r: np.ndarray) -> float: + """Heading of a rotation matrix (rotation of +x about +z, ``atan2(R[1,0], R[0,0])``).""" + r = np.asarray(r, dtype=np.float64) + return math.atan2(r[1, 0], r[0, 0]) + + +def wrap_angle(a: Any) -> Any: + """Wrap angles to [-pi, pi).""" + return (np.asarray(a, dtype=np.float64) + math.pi) % (2.0 * math.pi) - math.pi + + +def mmdet_yaw_to_ros(yaw_net: Any) -> np.ndarray: + """``ros_utils.cpp:55``: ``const float yaw = -box3d.yaw - pi / 2`` (float input, double arithmetic, float + result). Returns float32 radians, not wrapped (as Autoware).""" + y = np.asarray(yaw_net, dtype=np.float32).astype(np.float64) + return (-y - math.pi / 2.0).astype(np.float32) + + +def ros_yaw_to_mmdet(yaw_ros: Any) -> np.ndarray: + """Inverse of :func:`mmdet_yaw_to_ros` (float64): ``yaw_net = -yaw_ros - pi/2``.""" + return -np.asarray(yaw_ros, dtype=np.float64) - math.pi / 2.0 diff --git a/code/tt_depthpro2/ttaw/golden.py b/code/tt_depthpro2/ttaw/golden.py new file mode 100644 index 0000000000000000000000000000000000000000..e00fb389b91d619962eb1fae59d72751ed7aec6a --- /dev/null +++ b/code/tt_depthpro2/ttaw/golden.py @@ -0,0 +1,488 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C06 goldens: golden tensor files, a tap registry, gates that are never loosened, JSON compare reports. + +- **Golden files** are ``.npz`` (loaded with ``allow_pickle=False``) holding named tensors ("taps") and an optional + JSON metadata record under the key ``__meta__`` (source file hashes, reference script, sample, date). +- **Taps** are named intermediates recorded by :class:`TapRegistry` from the CPU reference or from an *eager* + device run (never inside a trace capture: a traced intermediate is freed at the end of the capture). +- **Gates** (PLAN.md section 0.3): thresholds are declared in the test (from the spec targets) and frozen in a JSON + file next to the test at the first green run (``test_pcc_device.py`` -> ``test_pcc_device.gates.json``). From then + on a declaration looser than the frozen threshold raises :class:`GateLoosenedError`; tightening is allowed and + re-frozen. Changing a frozen gate means editing the JSON by hand and disclosing it (VERIFICATION_.md). +- **Reports**: :class:`CompareReport` collects per-tap statistics and gate verdicts and writes JSON. + +numpy only (device tensors are converted through :func:`.tensors.to_numpy`, which imports ttnn lazily). +""" +from __future__ import annotations + +import contextlib +import datetime as _dt +import fnmatch +import json +import math +import os +import sys +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Union + +import numpy as np + +from . import metrics as _m +from .weights import file_sha256 + +__all__ = [ + "save_goldens", + "load_goldens", + "Goldens", + "TapRegistry", + "Gate", + "GateResult", + "GateLoosenedError", + "GateRegistry", + "METRICS", + "DIRECTIONS", + "TapComparison", + "CompareReport", + "compare_taps", +] + +PathLike = Union[str, os.PathLike] +META_KEY = "__meta__" + + +def _now() -> str: + return _dt.datetime.now(_dt.timezone.utc).isoformat(timespec="seconds") + + +def _host(value: Any) -> np.ndarray: + from .tensors import to_numpy + + return np.asarray(to_numpy(value)) + + +def _atomic_write_text(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") + tmp.write_text(text) + os.replace(tmp, path) + + +# --------------------------------------------------------------------------------------------- golden files + +def save_goldens(path: PathLike, tensors: Mapping[str, Any], meta: Optional[Mapping[str, Any]] = None, *, + compress: bool = False) -> Path: + """Write ``tensors`` (numpy / torch / ttnn) and ``meta`` (JSON-able) to an ``.npz`` file.""" + path = Path(path) + arrays = {str(k): _host(v) for k, v in tensors.items()} + if META_KEY in arrays: + raise ValueError(f"{META_KEY!r} is reserved for metadata") + arrays[META_KEY] = np.array(json.dumps(dict(meta or {}), sort_keys=True, default=str)) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(f".{path.stem}.{os.getpid()}.tmp.npz") + (np.savez_compressed if compress else np.savez)(tmp, **arrays) + os.replace(tmp, path) + return path + + +class Goldens(Mapping): + """Read-only, lazily loaded golden tensors of one ``.npz`` file (``with load_goldens(p) as g: g["neck"]``).""" + + def __init__(self, path: PathLike): + self.path = Path(path) + self._npz = np.load(self.path, allow_pickle=False) + self._cache: Dict[str, np.ndarray] = {} + self.meta: Dict[str, Any] = (json.loads(str(self._npz[META_KEY])) if META_KEY in self._npz.files else {}) + self._sha256: Optional[str] = None + + @property + def sha256(self) -> str: + if self._sha256 is None: + self._sha256 = file_sha256(self.path) + return self._sha256 + + def __getitem__(self, name: str) -> np.ndarray: + if name == META_KEY or name not in self._npz.files: + raise KeyError(f"{name!r} not in {self.path.name}; have {sorted(self)[:20]}") + if name not in self._cache: + self._cache[name] = self._npz[name] + return self._cache[name] + + def __iter__(self) -> Iterator[str]: + return (k for k in self._npz.files if k != META_KEY) + + def __len__(self) -> int: + return sum(1 for _ in self) + + def close(self) -> None: + self._npz.close() + + def __enter__(self) -> "Goldens": + return self + + def __exit__(self, *exc) -> None: + self.close() + + +def load_goldens(path: PathLike) -> Goldens: + return Goldens(path) + + +# ------------------------------------------------------------------------------------------------- taps + +class TapRegistry: + """Records named intermediates. ``tap(name, value)`` returns ``value`` unchanged, so it can be inlined:: + + taps = TapRegistry(include=["backbone.*", "neck"]) + x = taps.tap("backbone.layer1", layer1(x)) # stored as numpy (host read for device tensors) + with taps.scope("head"): + y = taps.tap("cls", cls_head(x)) # recorded as "head.cls" + taps.save("golden/sample0_taps.npz", meta={...}) + + A disabled registry (``TapRegistry(enabled=False)``, or :data:`NULL_TAPS`) does nothing, so production code can + keep its ``tap`` calls. Device tensors are read immediately (they may be deallocated later by the model); + calling ``tap`` on a device tensor while a trace capture is active raises.""" + + def __init__(self, enabled: bool = True, *, include: Sequence[str] = ("*",), exclude: Sequence[str] = ()): + self.enabled = enabled + self.include = tuple(include) + self.exclude = tuple(exclude) + self._prefix: List[str] = [] + self._values: Dict[str, np.ndarray] = {} + + def _full(self, name: str) -> str: + return ".".join(self._prefix + [name]) + + def wants(self, name: str) -> bool: + """Whether ``name`` (full dotted name) would be recorded.""" + return (self.enabled and any(fnmatch.fnmatchcase(name, p) for p in self.include) + and not any(fnmatch.fnmatchcase(name, p) for p in self.exclude)) + + def tap(self, name: str, value: Any) -> Any: + if not self.enabled: + return value + full = self._full(name) + if not self.wants(full): + return value + ttnn = sys.modules.get("ttnn") + if ttnn is not None and isinstance(value, getattr(ttnn, "Tensor", ())): + if value.storage_type() == ttnn.StorageType.DEVICE and ttnn.is_trace_capture_active(value.device()): + raise RuntimeError(f"tap {full!r} inside a trace capture: return it as a trace output instead") + self._values[full] = _host(value) + return value + + @contextlib.contextmanager + def scope(self, name: str) -> Iterator["TapRegistry"]: + self._prefix.append(name) + try: + yield self + finally: + self._prefix.pop() + + def names(self) -> List[str]: + return list(self._values) + + def __contains__(self, name: str) -> bool: + return name in self._values + + def __getitem__(self, name: str) -> np.ndarray: + return self._values[name] + + def items(self): + return self._values.items() + + def to_dict(self) -> Dict[str, np.ndarray]: + return dict(self._values) + + def clear(self) -> None: + self._values.clear() + + def save(self, path: PathLike, meta: Optional[Mapping[str, Any]] = None, *, compress: bool = False) -> Path: + return save_goldens(path, self._values, meta, compress=compress) + + +NULL_TAPS = TapRegistry(enabled=False) + +# ------------------------------------------------------------------------------------------------ gates + +# metric name -> (function(test, ref, **kw) -> float, direction): "min" = higher is better (value >= threshold) +METRICS: Dict[str, Any] = { + "pcc": (_m.pcc, "min"), + "masked_pcc": (_m.masked_pcc, "min"), + "argmax_agreement": (_m.argmax_agreement, "min"), + "label_agreement": (_m.label_agreement, "min"), + "mask_iou": (_m.mask_iou, "min"), + "max_abs": (lambda t, r: _m.error_stats(t, r)["max_abs"], "max"), + "mean_abs": (lambda t, r: _m.error_stats(t, r)["mean_abs"], "max"), + "rel_l2": (lambda t, r: _m.error_stats(t, r)["rel_l2"], "max"), +} + +# The direction of every metric name a gate may use without spelling it out (the METRICS above plus the scalars +# recorded with CompareReport.add_value). A bare-number gate on any other metric is refused rather than guessed: +# a guessed "min" on an error metric (ADE, max |error|) would pass exactly the results it is meant to fail. +DIRECTIONS: Dict[str, str] = { + **{name: direction for name, (_, direction) in METRICS.items()}, + **dict.fromkeys(("valid_row_pcc", "agreement", "iou", "miou", "mean_iou", "recall", "precision", "topk_overlap", + "topk_set_overlap"), "min"), + **dict.fromkeys(("max_abs_err", "ade", "fde", "center_err", "center_err_max", "center_err_mean", "score_err", + "score_err_max", "score_err_mean"), "max"), +} + + +@dataclass(frozen=True) +class Gate: + """``direction="min"``: pass when ``value >= threshold`` (PCC, agreement, IoU, recall); ``"max"``: pass when + ``value <= threshold`` (errors, ADE/FDE). NaN never passes.""" + + threshold: float + direction: str = "min" + metric: str = "pcc" + + def __post_init__(self) -> None: + if self.direction not in ("min", "max"): + raise ValueError(f"gate direction {self.direction!r}: expected 'min' or 'max'") + object.__setattr__(self, "threshold", float(self.threshold)) + + @classmethod + def of(cls, spec: Union["Gate", float, int, Sequence, Mapping], metric: Optional[str] = None) -> "Gate": + """``0.999`` | ``(0.999, "min")`` | ``(0.05, "max", "max_abs")`` | ``{"threshold": ..., ...}`` | Gate. + A bare number takes the direction of ``metric`` (default ``pcc``) from :data:`DIRECTIONS` and raises + ``ValueError`` for a metric whose direction is unknown; a direction that contradicts a known metric's + (e.g. a ``"max"`` PCC gate) raises too.""" + if isinstance(spec, Gate): + gate = spec + elif isinstance(spec, Mapping): + gate = cls(**spec) + elif isinstance(spec, (int, float)): + name = metric or "pcc" + if name not in DIRECTIONS: + raise ValueError(f"gate {spec!r} on metric {name!r}: its direction is unknown; give " + f"(threshold, 'min' | 'max', {name!r})") + gate = cls(float(spec), DIRECTIONS[name], name) + else: + parts = list(spec) + gate = cls(*parts) if len(parts) == 3 else cls(parts[0], parts[1], metric or "pcc") + known = DIRECTIONS.get(gate.metric) + if known is not None and gate.direction != known: + better = "higher" if known == "min" else "lower" + raise ValueError(f"gate {gate}: {gate.metric!r} is a {known!r} metric ({better} is better)") + return gate + + def passes(self, value: float) -> bool: + if value is None or (isinstance(value, float) and math.isnan(value)): + return False + return value >= self.threshold if self.direction == "min" else value <= self.threshold + + def looser_than(self, other: "Gate") -> bool: + """True if this gate accepts something ``other`` rejects (same direction), or the direction differs.""" + if self.direction != other.direction or self.metric != other.metric: + return True + return self.threshold < other.threshold if self.direction == "min" else self.threshold > other.threshold + + +@dataclass +class GateResult: + name: str + value: Optional[float] + gate: Gate + passed: bool + newly_frozen: bool = False + + def __str__(self) -> str: + op = ">=" if self.gate.direction == "min" else "<=" + v = "nan" if self.value is None else f"{self.value:.6g}" + return f"{'PASS' if self.passed else 'FAIL'} {self.name}: {self.gate.metric} {v} {op} {self.gate.threshold:g}" + + +class GateLoosenedError(AssertionError): + """A declared gate is looser than the threshold frozen at the first green run.""" + + +class GateRegistry: + """Declared gates + the JSON record of frozen gates next to the test file. + + Usage in a device test:: + + GATES = GateRegistry.for_test(__file__, {"backbone": 0.999, "head.reg": 0.99, "dets.recall": (0.95, "min")}) + + @pytest.mark.parametrize("stage", GATES.names()) + def test_stage(stage, stage_outputs): + GATES.require(stage, pcc(*stage_outputs[stage])) # AssertionError on failure; frozen on first pass + + ``write=False`` (or ``TTAW_GATES_READONLY=1``) never writes the JSON (CI / verification runs).""" + + VERSION = 1 + + def __init__(self, path: PathLike, gates: Optional[Mapping[str, Any]] = None, *, write: Optional[bool] = None): + self.path = Path(path) + if write is None: + write = os.environ.get("TTAW_GATES_READONLY", "0").strip() in ("", "0", "false", "no") + self.write = bool(write) + self.declared: Dict[str, Gate] = {k: Gate.of(v) for k, v in (gates or {}).items()} + self.frozen: Dict[str, Dict[str, Any]] = {} + if self.path.is_file(): + data = json.loads(self.path.read_text()) + self.frozen = dict(data.get("gates", {})) + self.results: List[GateResult] = [] + loosened = [] + for name, g in self.declared.items(): + if name in self.frozen and g.looser_than(self._frozen_gate(name)): + f = self._frozen_gate(name) + loosened.append(f"{name}: declared {g.direction} {g.threshold:g} ({g.metric}) vs frozen " + f"{f.direction} {f.threshold:g} ({f.metric})") + if loosened: + raise GateLoosenedError(f"gates in {self.path.name} may never be loosened once recorded: " + + "; ".join(loosened)) + + @classmethod + def for_test(cls, test_file: PathLike, gates: Optional[Mapping[str, Any]] = None, **kwargs: Any) -> "GateRegistry": + """Registry stored as ``.gates.json`` next to ``test_file`` (pass ``__file__``).""" + p = Path(test_file) + return cls(p.with_name(p.stem + ".gates.json"), gates, **kwargs) + + def _frozen_gate(self, name: str) -> Gate: + rec = self.frozen[name] + return Gate(rec["threshold"], rec["direction"], rec["metric"]) + + def names(self) -> List[str]: + return sorted(set(self.declared) | set(self.frozen)) + + def gate(self, name: str) -> Gate: + """The effective gate: the declared one (never looser than the frozen one), else the frozen one.""" + if name in self.declared: + return self.declared[name] + if name in self.frozen: + return self._frozen_gate(name) + raise KeyError(f"no gate {name!r} declared or frozen in {self.path.name}") + + def check(self, name: str, value: Optional[float], gate: Optional[Any] = None) -> GateResult: + """Evaluate ``value``; on a pass, freeze the gate if it is new or tighter than the frozen one.""" + g = Gate.of(gate) if gate is not None else self.gate(name) + if name in self.frozen and g.looser_than(self._frozen_gate(name)): + raise GateLoosenedError(f"gate {name!r} {g} is looser than the frozen {self.frozen[name]}") + v = None if value is None else float(value) + passed = g.passes(v) + newly = False + if passed and (name not in self.frozen or self._frozen_gate(name) != g): + self.frozen[name] = {**asdict(g), "value_at_freeze": v, "frozen_at": _now()} + newly = True + if self.write: + self.save() + result = GateResult(name, v, g, passed, newly) + self.results.append(result) + return result + + def require(self, name: str, value: Optional[float], gate: Optional[Any] = None) -> GateResult: + """:meth:`check`, raising ``AssertionError`` when the gate fails.""" + result = self.check(name, value, gate) + if not result.passed: + raise AssertionError(str(result)) + return result + + def save(self) -> None: + body = {"version": self.VERSION, "note": "Frozen at the first green run; never loosen (PLAN.md 0.3).", + "gates": dict(sorted(self.frozen.items()))} + _atomic_write_text(self.path, json.dumps(body, indent=1, sort_keys=False) + "\n") + + +# ----------------------------------------------------------------------------------------------- reports + +@dataclass +class TapComparison: + name: str + metric: str + value: Optional[float] + gate: Optional[Dict[str, Any]] + passed: Optional[bool] + stats: Dict[str, Any] = field(default_factory=dict) + note: str = "" + + +class CompareReport: + """Per-tap comparison records -> JSON (``logs//compare_.json``) and a text table.""" + + def __init__(self, title: str = "", meta: Optional[Mapping[str, Any]] = None, + gates: Optional[GateRegistry] = None): + self.title = title + self.meta = dict(meta or {}) + self.gates = gates + self.entries: List[TapComparison] = [] + + def _gate_for(self, name: str, gate: Any, metric: str) -> Optional[Gate]: + if gate is not None: + return Gate.of(gate, metric) + if self.gates is not None and name in self.gates.names(): + return self.gates.gate(name) + return None + + def add(self, name: str, test: Any, ref: Any, *, metric: str = "pcc", gate: Any = None, + **metric_kwargs: Any) -> TapComparison: + """Compare two tensors with ``metric`` (a :data:`METRICS` name); always records the error statistics.""" + t, r = _host(test), _host(ref) + stats: Dict[str, Any] = {"shape_test": list(t.shape), "shape_ref": list(r.shape), + "dtype_test": str(t.dtype), "dtype_ref": str(r.dtype)} + note = "" + if t.shape == r.shape: + stats.update(_m.error_stats(t, r)) + fn = METRICS[metric][0] + value: Optional[float] = float(fn(t, r, **metric_kwargs)) + else: + value, note = None, "shape mismatch" + return self._record(name, metric, value, gate, stats, note) + + def add_value(self, name: str, value: Optional[float], *, metric: str, gate: Any = None, + stats: Optional[Mapping[str, Any]] = None) -> TapComparison: + """Record an already computed scalar (detection recall, ADE, argmax agreement ...).""" + return self._record(name, metric, None if value is None else float(value), gate, dict(stats or {}), "") + + def _record(self, name: str, metric: str, value: Optional[float], gate: Any, stats: Dict[str, Any], + note: str) -> TapComparison: + g = self._gate_for(name, gate, metric) + passed: Optional[bool] = None + if g is not None: + passed = (self.gates.check(name, value, g).passed if self.gates is not None else g.passes(value)) + entry = TapComparison(name, metric, value, None if g is None else asdict(g), passed, stats, note) + self.entries.append(entry) + return entry + + @property + def passed(self) -> bool: + """All gated entries passed (ungated entries are informational).""" + return all(e.passed for e in self.entries if e.passed is not None) + + def to_dict(self) -> Dict[str, Any]: + return {"title": self.title, "created": _now(), "meta": self.meta, "passed": self.passed, + "entries": [asdict(e) for e in self.entries]} + + def save_json(self, path: PathLike) -> Path: + path = Path(path) + _atomic_write_text(path, json.dumps(self.to_dict(), indent=1, default=str) + "\n") + return path + + def table(self) -> str: + rows = [f"{self.title}".strip(), f"{'name':40s} {'metric':16s} {'value':>12s} {'gate':>14s} verdict"] + for e in self.entries: + gate = "" + if e.gate is not None: + gate = (">=" if e.gate["direction"] == "min" else "<=") + f"{e.gate['threshold']:g}" + val = "nan" if e.value is None else f"{e.value:.6g}" + verdict = {True: "PASS", False: "FAIL", None: "-"}[e.passed] + rows.append(f"{e.name:40s} {e.metric:16s} {val:>12s} {gate:>14s} {verdict} {e.note}".rstrip()) + return "\n".join(r for r in rows if r) + + +def compare_taps(test: Mapping[str, Any], golden: Mapping[str, Any], *, gates: Optional[Any] = None, + metric: str = "pcc", names: Optional[Sequence[str]] = None, title: str = "", + meta: Optional[Mapping[str, Any]] = None) -> CompareReport: + """Compare every tap present in both mappings (or ``names``). ``gates``: a :class:`GateRegistry` or a + ``{name: gate spec}`` mapping. Taps missing on either side are recorded as failures when gated.""" + registry = gates if isinstance(gates, GateRegistry) else None + plain = {} if registry is not None or gates is None else {k: Gate.of(v, metric) for k, v in gates.items()} + report = CompareReport(title, meta, registry) + for name in (names if names is not None else [n for n in golden if n in test]): + if name not in test or name not in golden: + report.add_value(name, None, metric=metric, gate=plain.get(name), + stats={"missing": "test" if name not in test else "golden"}) + continue + report.add(name, test[name], golden[name], metric=metric, gate=plain.get(name)) + return report diff --git a/code/tt_depthpro2/ttaw/image.py b/code/tt_depthpro2/ttaw/image.py new file mode 100644 index 0000000000000000000000000000000000000000..438db2933fdb08d3d61851c7a252b84c37093566 --- /dev/null +++ b/code/tt_depthpro2/ttaw/image.py @@ -0,0 +1,666 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C14 image pre-processing: bit-exact host emulations of the Autoware camera nodes' resize kernels, driven by +per-source-size lookup tables (LUTs) that are computed once and cached. + +Each preset reproduces one deployed CUDA / OpenCV routine exactly (integer outputs equal, not "close"), because a +standard resize in its place changes the network input enough to fail the PCC gates (YOLOX: ``cv2.resize`` drops the +detection-output PCC to 0.94, research/yolox/SPEC.md section 3). The tables hold everything that depends only on the +source and destination sizes (source indices, interpolation weights, letterbox geometry); applying them is a few +vectorised numpy passes over the image. numpy only; no ttnn, no torch, no OpenCV. + +Presets (PLAN.md C14; the other camera ports add theirs here): + +========================== ========================================================================================= +``yolox_letterbox`` autoware_tensorrt_yolox ``resize_bilinear_letterbox_nhwc_to_nchw32_batch_kernel`` + (autoware_universe @ 9ceaccf, ``perception/autoware_tensorrt_yolox/src/preprocess.cu:43-129``, + launched by ``tensorrt_yolox.cpp:243-332``): a "bilinear" resize with inverted, + half-magnitude weights, float -> int truncation between the horizontal and vertical passes, + ``lroundf``, top-left letterbox padded with 114, BGR kept, no normalisation. +``bevdet_nearest_crop`` the ``bevdet::Preprocess`` TensorRT plugin of autoware_tensorrt_bevdet (``bevdet_vendor`` + 0.2.1; research/bevdet/SPEC.md section 3.2): nearest resize by r = 0.44f + crop (140, 0) + of the 1600x900 image, ``roundf(i / r + crop_h / r)`` rows / columns in float32, planar + B, G, R uint8 (the normalisation ``bevdet_normalize`` is separate: device-side in the TT + port). The node's ``cv::resize`` of non-1600x900 images to 1600x900 stays with the caller. +``bevformer_preprocess`` autoware_tensorrt_bevformer's ``preprocessing_pipeline`` (autoware_universe @ 9ceaccf, + ``src/preprocessing/normalize_multiview_image.cpp:70-95`` + + ``augmentation_transforms.cpp:90-222``; research/bevformer/SPEC.md section 3.1): + normalise FIRST (BGR uint8 -> float, ``(x - mean_c) / std_c``, BGR mean, std 1), then + ``cv::resize`` x0.8 with INTER_LINEAR **on float data** (1600x900 -> 1280x720), then pad + bottom / right with 0 (normalised space) to a multiple of 32 (1280x736), CHW. The node's + ``cv::resize`` of non-1600x900 uint8 images to 1600x900 stays with the caller. +========================== ========================================================================================= + +Exactness notes for ``yolox_letterbox`` (all arithmetic is float32 in the kernel): + +- ``scale = min(dst_w / (float)src_w, dst_h / (float)src_h)``; ``r_h = (int)(scale * src_h)``, + ``r_w = (int)(scale * src_w)``; the kernel receives ``k = (float)(1.0 / (double)scale)`` (``preprocess.cu:121-128``). +- per output row ``h``: ``c = k * (float)(h + 0.5)``, ``src_row = clamp(lroundf(c) - 1, 0, src_h - 2)``, + weight ``t = (1 + lroundf(c) - c) / 2`` (float32), and the same per column (``preprocess.cu:48-59, 77-88``). +- ``lerp1d(a, b, t) = fma(t, b, fma(-t, a, a))`` with float operands (CUDA's float overload, i.e. ``fmaf``: + one rounding per call); the horizontal results are truncated to int before the vertical ``lerp1d`` + (``lerp1d`` takes ``int a, int b``), and the result is ``lroundf``-ed (``preprocess.cu:43-46, 57, 101-103``). +- ``t`` lies in [0.25, 0.75], so ``t`` is a multiple of 2**-25 and ``a - t*a`` / ``t*b + inner`` with integer + ``a, b`` in [0, 255] need at most 34 significant bits: float64 holds them exactly, and one ``astype(float32)`` is + exactly the single rounding of ``fmaf``. +- Rows ``h >= r_h`` and columns ``w >= r_w`` are 114 (``preprocess.cu:109-110``); the output values are integers in + [0, 255], so this module returns uint8 (the network input is ``float(value)``, ``norm_factor`` 1.0). + +Verified against two independent scalar transliterations of the CUDA source (``common/tests/host/test_image_host.py`` +and research/yolox/scripts/{check_preprocess,verify_preproc_scalar}.py: 0 mismatches). Residual uncertainty, from the +SPEC: if nvcc picked the double ``fma`` overload, 0-2 of 3000 samples would differ by 1 (not testable without CUDA). + +Exactness notes for ``bevformer_preprocess`` (float32 data; OpenCV's float INTER_LINEAR path): + +- normalisation: ``Mat - mean`` / ``std`` evaluates as ``convertTo(alpha = 1/std, beta = -mean/std)`` with float + ``alpha`` / ``beta`` (one fused multiply-add per value); with the deployed std 1 it is ``x - float(mean_c)``. +- resize coefficients (``resize.cpp``): ``scale = 1.0 / ((double)dst / src)``, ``f = (float)((d + 0.5) * scale - + 0.5)``, ``s = floor(f)``, ``w = f - s`` (float), clamped to the border (``s < 0`` -> ``s = 0, w = 0``; + ``s >= src - 1`` -> ``s = src - 1, w = 0``); the destination size is ``(int)(src * 0.8f)`` in float. +- each pass is ``fma(x1 - x0, w, x0)`` in float32 (the difference rounded once, then one rounding of the fused + product-sum), horizontal pass first, then vertical. This is what OpenCV 4.8.1 and 4.11.0 compute on this x86-64 + host (AVX2 + FMA) bit for bit for every x0.8 down-scale, on arbitrary float images (not just uint8 - mean): the + plain two-product form ``x0 * (1 - w) + x1 * w`` differs from it in about 10 % of the samples by 1 ulp + (``tests/host/test_image_bevformer_host.py`` holds both checks). The weights of a x0.8 resize are multiples of + 1/8, so float64 holds every fused product-sum exactly and one ``astype(float32)`` is the single rounding. OpenCV + computes the coefficients of other scales differently, so :func:`opencv_linear_lut` refuses them by default. +""" +from __future__ import annotations + +import threading +from collections import OrderedDict +from dataclasses import dataclass +from typing import Any, Callable, Dict, Hashable, Optional, Tuple + +import numpy as np + +__all__ = [ + "LetterboxGeometry", + "YoloxLetterboxLUT", + "yolox_letterbox", + "yolox_letterbox_geometry", + "yolox_letterbox_lut", + "lroundf", + "f32", + "LUTCache", + "PRESETS", + "YOLOX_PAD_VALUE", + "NearestCropLUT", + "bevdet_nearest_lut", + "bevdet_nearest_crop", + "bevdet_normalize", + "BEVDET_MEAN", + "BEVDET_STD", + "LinearResizeLUT", + "opencv_linear_lut", + "opencv_resize_linear_f32", + "bevformer_input_geometry", + "bevformer_normalize", + "bevformer_preprocess", + "BEVFORMER_MEAN_BGR", + "BEVFORMER_STD", +] + +F32 = np.float32 +YOLOX_PAD_VALUE = 114 # preprocess.cu:109-110 (letterbox fill), the YOLOX training pad value + + +def f32(x: Any) -> np.ndarray: + """``x`` rounded once to float32 (round-to-nearest-even), as a numpy float32 scalar or array.""" + return np.asarray(x).astype(F32) + + +def lroundf(x: Any) -> np.ndarray: + """C ``lroundf``: round half away from zero, for float32 inputs (exact in float64). Returns int64.""" + x = np.asarray(x, dtype=np.float64) + return (np.sign(x) * np.floor(np.abs(x) + 0.5)).astype(np.int64) + + +class LUTCache: + """A small thread-safe LRU of tables keyed by the source / destination sizes (a camera stream keeps its size, + so the table is built once per stream; Autoware re-creates its buffers only when the source size changes, + ``tensorrt_yolox.cpp:253-291``).""" + + def __init__(self, maxsize: int = 8): + self.maxsize = int(maxsize) + self._items: "OrderedDict[Hashable, Any]" = OrderedDict() + self._lock = threading.Lock() + self.hits = 0 + self.misses = 0 + + def get(self, key: Hashable, make: Callable[[], Any]) -> Any: + with self._lock: + if key in self._items: + self._items.move_to_end(key) + self.hits += 1 + return self._items[key] + value = make() # outside the lock: building a table takes a few ms + with self._lock: + self.misses += 1 + self._items[key] = value + self._items.move_to_end(key) + while len(self._items) > self.maxsize: + self._items.popitem(last=False) + return value + + def clear(self) -> None: + with self._lock: + self._items.clear() + self.hits = self.misses = 0 + + def __len__(self) -> int: + return len(self._items) + + +# ------------------------------------------------------------------------------------------- YOLOX letterbox + + +@dataclass(frozen=True) +class LetterboxGeometry: + """Where the source image lands in the network input, and what the decoder and the mask crop use. + + ``scale`` is the float32 scale of ``preprocess.cu:121`` (also ``scales_`` of ``tensorrt_yolox.cpp:285``, used to + map boxes back, and the mask scale of ``tensorrt_yolox.cpp:528-536``); ``resized_hw`` = ``(r_h, r_w)``, the + un-letterboxed region at the top-left of the ``dst_hw`` canvas. Autoware's mask crop ``(out_h, out_w)`` = + ``((int)(src_h * scale), (int)(src_w * scale))`` is the same pair (float multiplication commutes).""" + + src_hw: Tuple[int, int] + dst_hw: Tuple[int, int] + scale: float # exact float32 value, stored as a Python float + resized_hw: Tuple[int, int] + pad_value: int = YOLOX_PAD_VALUE + + @property + def scale_f32(self) -> np.float32: + return F32(self.scale) + + @property + def mask_hw(self) -> Tuple[int, int]: + """``(out_h, out_w)`` of Autoware's mask (``getMaskImageGpu``): the un-letterboxed region.""" + return self.resized_hw + + def to_dict(self) -> Dict[str, Any]: + return {"src_hw": list(self.src_hw), "dst_hw": list(self.dst_hw), "scale": self.scale, + "scale_f32_hex": F32(self.scale).tobytes()[::-1].hex(), "resized_hw": list(self.resized_hw), + "mask_hw": list(self.mask_hw), "pad_value": self.pad_value, + "letterbox": "top-left (padding at the bottom / right)"} + + +def yolox_letterbox_geometry(src_h: int, src_w: int, dst_h: int = 960, dst_w: int = 960, + pad_value: int = YOLOX_PAD_VALUE) -> LetterboxGeometry: + """Letterbox geometry of ``preprocess.cu:121-123`` (float32 scale, int truncation).""" + src_h, src_w, dst_h, dst_w = int(src_h), int(src_w), int(dst_h), int(dst_w) + if src_h < 2 or src_w < 2: + raise ValueError(f"the Autoware resize needs a source of at least 2x2 pixels, got {src_w}x{src_h}") + if dst_h < 1 or dst_w < 1: + raise ValueError(f"bad destination size {dst_w}x{dst_h}") + scale = min(F32(dst_w) / F32(src_w), F32(dst_h) / F32(src_h)) # float32 divisions + scale = F32(scale) + r_h = int(F32(scale * F32(src_h))) + r_w = int(F32(scale * F32(src_w))) + return LetterboxGeometry((src_h, src_w), (dst_h, dst_w), float(scale), (min(r_h, dst_h), min(r_w, dst_w)), + int(pad_value)) + + +def _axis_table(n_dst: int, n_src: int, k: np.float32) -> Tuple[np.ndarray, np.ndarray]: + """Source index and weight of every destination row (or column): ``preprocess.cu:48-51, 77-88``.""" + c = (k * (np.arange(n_dst) + 0.5).astype(F32)).astype(F32) # centroid = scale * (float)(h + 0.5) + rc = lroundf(c) + idx = rc - 1 + idx = np.where(idx < 0, 0, idx) + idx = np.where(idx >= n_src - 1, n_src - 2, idx) + weight = ((F32(1) + rc.astype(F32)).astype(F32) - c).astype(F32) # 1 + lroundf(c) - c (float32) + weight = (weight / F32(2)).astype(F32) + return idx.astype(np.int64), weight + + +@dataclass(frozen=True) +class YoloxLetterboxLUT: + """The per-size tables of the YOLOX letterbox: source row / column of every destination row / column and the + float32 weights. Build with :func:`yolox_letterbox_lut` (cached); apply with :meth:`apply`.""" + + geometry: LetterboxGeometry + rows: np.ndarray # (r_h,) int64: source row hi (hi + 1 is the second tap) + row_w: np.ndarray # (r_h,) float32: vertical weight + cols: np.ndarray # (r_w,) int64: source column wi + col_w: np.ndarray # (r_w,) float32: horizontal weight + k: float # the kernel's float32 ``scale`` argument (1 / scale) + + def apply(self, image: np.ndarray, *, out: Optional[np.ndarray] = None, chunk_rows: int = 96) -> np.ndarray: + """Letterbox one BGR uint8 image ``(src_h, src_w, 3)`` (any channel count) -> uint8 ``(dst_h, dst_w, C)`` + HWC, channel order unchanged. ``out`` (uint8, that shape) is written in place when given.""" + g = self.geometry + img = np.asarray(image) + if img.ndim != 3 or img.dtype != np.uint8 or tuple(img.shape[:2]) != g.src_hw: + raise ValueError(f"expected a uint8 ({g.src_hw[0]}, {g.src_hw[1]}, C) image, got {img.dtype} {img.shape}") + dst_h, dst_w = g.dst_hw + r_h, r_w = g.resized_hw + shape = (dst_h, dst_w, img.shape[2]) + if out is None: + out = np.empty(shape, np.uint8) + elif out.shape != shape or out.dtype != np.uint8: + raise ValueError(f"out must be uint8 {shape}, got {out.dtype} {out.shape}") + out[r_h:] = g.pad_value + out[:r_h, r_w:] = g.pad_value + if r_h == 0 or r_w == 0: + return out + tw = self.col_w.astype(np.float64)[None, :, None] # exact float32 values + cols0, cols1 = self.cols, self.cols + 1 + for start in range(0, r_h, max(1, int(chunk_rows))): + stop = min(r_h, start + int(chunk_rows)) + hi = self.rows[start:stop] + # horizontal pass on the source rows this chunk needs (hi and hi + 1), each row once + need = np.unique(np.concatenate([hi, hi + 1])) + src = img[need] # (R, src_w, C) uint8 + a = src[:, cols0].astype(np.float64) # (R, r_w, C) + b = src[:, cols1].astype(np.float64) + inner = (a - tw * a).astype(F32) # fmaf(-t, a, a) + horiz = (tw * b + inner).astype(F32) # fmaf(t, b, inner) + horiz = np.trunc(horiz).astype(np.float64) # lerp1d(int a, int b, ...): truncation + pos0 = np.searchsorted(need, hi) + pos1 = np.searchsorted(need, hi + 1) + a1, b1 = horiz[pos0], horiz[pos1] # (rows, r_w, C) + th = self.row_w[start:stop].astype(np.float64)[:, None, None] + inner = (a1 - th * a1).astype(F32) + r = (th * b1 + inner).astype(F32) # second lerp1d, float32 + out[start:stop, :r_w] = np.floor(r.astype(np.float64) + 0.5) # lroundf (r >= 0) + return out + + +_YOLOX_LUTS = LUTCache(maxsize=8) + + +def yolox_letterbox_lut(src_h: int, src_w: int, dst_h: int = 960, dst_w: int = 960, + pad_value: int = YOLOX_PAD_VALUE) -> YoloxLetterboxLUT: + """The (cached) tables for one source size.""" + + def make() -> YoloxLetterboxLUT: + g = yolox_letterbox_geometry(src_h, src_w, dst_h, dst_w, pad_value) + k = F32(1.0 / np.float64(g.scale_f32)) # 1.0 / scale in double, passed as a float argument + rows, row_w = _axis_table(dst_h, g.src_hw[0], k) + cols, col_w = _axis_table(dst_w, g.src_hw[1], k) + r_h, r_w = g.resized_hw + return YoloxLetterboxLUT(g, rows[:r_h].copy(), row_w[:r_h].copy(), cols[:r_w].copy(), col_w[:r_w].copy(), + float(k)) + + return _YOLOX_LUTS.get(("yolox", int(src_h), int(src_w), int(dst_h), int(dst_w), int(pad_value)), make) + + +def yolox_letterbox(image: np.ndarray, dst_hw: Tuple[int, int] = (960, 960), *, pad_value: int = YOLOX_PAD_VALUE, + layout: str = "hwc", out: Optional[np.ndarray] = None) -> Tuple[np.ndarray, LetterboxGeometry]: + """Autoware YOLOX letterbox of one BGR8 image ``(H, W, 3)`` -> ``(uint8 image, geometry)``. + + ``layout``: ``"hwc"`` -> ``(dst_h, dst_w, 3)``; ``"nchw"`` -> ``(1, 3, dst_h, dst_w)`` (the ONNX ``images`` + layout; ``.astype(np.float32)`` is exactly the network input). The channel order is unchanged (Autoware feeds + BGR).""" + img = np.asarray(image) + lut = yolox_letterbox_lut(img.shape[0], img.shape[1], int(dst_hw[0]), int(dst_hw[1]), pad_value) + if layout == "hwc": + return lut.apply(img, out=out), lut.geometry + if layout == "nchw": + hwc = lut.apply(img) + res = np.ascontiguousarray(hwc.transpose(2, 0, 1)[None]) + if out is not None: + out[...] = res + return out, lut.geometry + return res, lut.geometry + raise ValueError(f"layout must be 'hwc' or 'nchw', got {layout!r}") + + +# ------------------------------------------------------------------------------------------- BEVDet nearest crop + +# Per-plane statistics of the BEVDet Preprocess plugin, applied to the B, G, R planes in this order: training loaded +# images as RGB (PIL) and its mmlabNormalize swapped them to BGR before applying the "RGB" ImageNet statistics, and +# the Autoware node feeds BGR planes with the same numbers (research/bevdet/SPEC.md section 3.1). +BEVDET_MEAN = (123.675, 116.28, 103.53) +BEVDET_STD = (58.395, 57.12, 57.375) + + +def _roundf(x: Any) -> np.ndarray: + """C ``roundf`` (half away from zero) of float32 values -> int64.""" + x = np.asarray(x, F32) + return (np.sign(x) * np.floor(np.abs(x) + F32(0.5))).astype(np.int64) + + +@dataclass(frozen=True) +class NearestCropLUT: + """The ``bevdet::Preprocess`` gather: output row ``i`` / column ``j`` reads source row ``rows[i]`` / column + ``cols[j]`` of the (already 1600x900) image. Build with :func:`bevdet_nearest_lut` (cached); apply with + :meth:`apply` (one HWC image) or :meth:`apply_planes` (planar ``[..., C, H, W]``).""" + + src_hw: Tuple[int, int] + dst_hw: Tuple[int, int] + crop_hw: Tuple[int, int] + resize: float # exact float32 ratio dst_w / src_w, stored as a Python float + rows: np.ndarray # (dst_h,) int64 + cols: np.ndarray # (dst_w,) int64 + + def apply(self, image: np.ndarray, *, channels: str = "rgb", out: Optional[np.ndarray] = None) -> np.ndarray: + """One ``(src_h, src_w, 3)`` uint8 image -> ``(3, dst_h, dst_w)`` uint8 B, G, R planes. ``channels`` is the + input's order: ``"rgb"`` (PIL / ``ttaw.io.load_image``) or ``"bgr"`` (OpenCV, cv_bridge ``bgr8``).""" + img = np.asarray(image) + if img.ndim != 3 or img.shape[2] != 3 or img.dtype != np.uint8 or tuple(img.shape[:2]) != self.src_hw: + raise ValueError(f"expected a uint8 ({self.src_hw[0]}, {self.src_hw[1]}, 3) image, got {img.dtype} " + f"{img.shape} (resize it to the source size first, like the node's cv::resize)") + if channels not in ("rgb", "bgr"): + raise ValueError(f"channels must be 'rgb' or 'bgr', got {channels!r}") + sub = img[self.rows][:, self.cols] # (dst_h, dst_w, 3) + order = [2, 1, 0] if channels == "rgb" else [0, 1, 2] # -> B, G, R + res = sub[:, :, order].transpose(2, 0, 1) + if out is None: + return np.ascontiguousarray(res) + shape = (3,) + tuple(self.dst_hw) + if out.shape != shape or out.dtype != np.uint8: + raise ValueError(f"out must be uint8 {shape}, got {out.dtype} {out.shape}") + out[...] = res + return out + + def apply_planes(self, planes: np.ndarray) -> np.ndarray: + """Planar ``[..., C, src_h, src_w]`` (any dtype) -> ``[..., C, dst_h, dst_w]``.""" + p = np.asarray(planes) + if tuple(p.shape[-2:]) != self.src_hw: + raise ValueError(f"expected planes [..., {self.src_hw[0]}, {self.src_hw[1]}], got {p.shape}") + return np.ascontiguousarray(p[..., self.rows, :][..., self.cols]) + + +_BEVDET_LUTS = LUTCache(maxsize=4) + + +def bevdet_nearest_lut(src_hw: Tuple[int, int] = (900, 1600), dst_hw: Tuple[int, int] = (256, 704), + crop_hw: Tuple[int, int] = (140, 0)) -> NearestCropLUT: + """The (cached) gather of the BEVDet Preprocess plugin: ``r = (float)dst_w / src_w`` (0.44f for the deployed + config, also the ONNX attribute ``resize_radio``), ``rows[i] = roundf(i / r + crop_h / r)``, + ``cols[j] = roundf(j / r + crop_w / r)``, every quantity float32 (deployed: rows 318, 320, 323, ..., 898 and + columns 0, 2, 5, 7, ..., 1598). ``crop_hw`` is the crop offset in RESIZED pixels (the yaml ``crop``, (h, w)).""" + src_h, src_w = int(src_hw[0]), int(src_hw[1]) + dst_h, dst_w = int(dst_hw[0]), int(dst_hw[1]) + crop_h, crop_w = int(crop_hw[0]), int(crop_hw[1]) + + def make() -> NearestCropLUT: + r = F32(F32(dst_w) / F32(src_w)) + off_h = F32(F32(crop_h) / r) + off_w = F32(F32(crop_w) / r) + rows = _roundf((np.arange(dst_h, dtype=F32) / r + off_h).astype(F32)) + cols = _roundf((np.arange(dst_w, dtype=F32) / r + off_w).astype(F32)) + if rows.min() < 0 or rows.max() >= src_h or cols.min() < 0 or cols.max() >= src_w: + raise ValueError(f"crop {crop_hw} with ratio {float(r)} reads outside the {src_w}x{src_h} source") + return NearestCropLUT((src_h, src_w), (dst_h, dst_w), (crop_h, crop_w), float(r), rows, cols) + + return _BEVDET_LUTS.get(("bevdet", src_h, src_w, dst_h, dst_w, crop_h, crop_w), make) + + +def bevdet_nearest_crop(image: np.ndarray, *, channels: str = "rgb", src_hw: Tuple[int, int] = (900, 1600), + dst_hw: Tuple[int, int] = (256, 704), crop_hw: Tuple[int, int] = (140, 0), + out: Optional[np.ndarray] = None) -> np.ndarray: + """One camera image at the source size (1600x900) -> its ``(3, 256, 704)`` uint8 B, G, R crop: exactly the + samples the BEVDet network sees before ``bevdet_normalize``.""" + return bevdet_nearest_lut(src_hw, dst_hw, crop_hw).apply(image, channels=channels, out=out) + + +def bevdet_normalize(crop: np.ndarray, mean: Any = BEVDET_MEAN, std: Any = BEVDET_STD) -> np.ndarray: + """``(x - mean[c]) / std[c]`` in float32 on B, G, R planes ``[..., 3, H, W]`` (the plugin's fp32 path; its fp16 + mode computes in ``__half``).""" + m = np.asarray(mean, F32).reshape(3, 1, 1) + s = np.asarray(std, F32).reshape(3, 1, 1) + return ((np.asarray(crop).astype(F32) - m) / s).astype(F32) + + +# ------------------------------------------------------------------------------------------- BEVFormer + +# autoware_tensorrt_bevformer config/bevformer.param.yaml data_params (= the BEVFormer training img_norm_cfg, +# DerryHub configs/bevformer/bevformer_small.py:19): caffe-style BGR means, std 1, to_rgb false +BEVFORMER_MEAN_BGR = (103.530, 116.280, 123.675) +BEVFORMER_STD = (1.0, 1.0, 1.0) + + +@dataclass(frozen=True) +class LinearResizeLUT: + """OpenCV ``cv::resize(..., INTER_LINEAR)`` of float32 data for one (source, destination) size pair: row / column + pairs and the float32 weight of the second tap (``resize.cpp`` coefficient loop; module docstring). Build with + :func:`opencv_linear_lut` (cached); apply with :meth:`apply` (HWC) or :meth:`apply_planes` (``[..., H, W]``).""" + + src_hw: Tuple[int, int] + dst_hw: Tuple[int, int] + rows0: np.ndarray # (dst_h,) int64 + rows1: np.ndarray # (dst_h,) int64 (clamped to the last row) + wy: np.ndarray # (dst_h,) float32 weight of rows1 + cols0: np.ndarray # (dst_w,) int64 + cols1: np.ndarray + wx: np.ndarray # (dst_w,) float32 weight of cols1 + + @staticmethod + def _lerp(x0: np.ndarray, x1: np.ndarray, w: Any, out: Optional[np.ndarray] = None) -> np.ndarray: + """``fma(x1 - x0, w, x0)`` in float32: the difference rounded once, the fused product-sum rounded once + (float64 holds ``d * w + x0`` exactly for weights that are multiples of 1/8). ``x1`` is overwritten.""" + d = np.subtract(x1, x0, out=x1) # float32: one rounding + t = d.astype(np.float64) + t *= w + t += x0 + if out is None: + return t.astype(F32) + out[...] = t # float64 -> float32: one rounding + return out + + @staticmethod + def _period(i0: np.ndarray, i1: np.ndarray, w: np.ndarray, n_src: int) -> Optional[Tuple[int, int]]: + """``(p_in, p_out)`` when the taps repeat every ``p_out`` outputs shifted by ``p_in`` inputs, both taps of + an output lie in one input block and no border clamp occurs (x0.8: 5 inputs -> 4 outputs), else None.""" + n_dst = len(i0) + for p_out in range(1, min(n_dst, 64) + 1): + if n_dst % p_out or (n_src * p_out) % n_dst: + continue + p_in = n_src * p_out // n_dst + base = (np.arange(n_dst) // p_out) * p_in + reps = n_dst // p_out + if (np.array_equal(i0 - base, np.tile(i0[:p_out], reps)) and np.array_equal(i1, i0 + 1) + and np.array_equal(w, np.tile(w[:p_out], reps)) and int(i1[:p_out].max()) < p_in): + return p_in, p_out + return None + + def _pass(self, p: np.ndarray, axis: int, i0: np.ndarray, i1: np.ndarray, w: np.ndarray) -> np.ndarray: + """One interpolation pass along ``axis`` (-1: columns, -2: rows) of a contiguous ``p`` [..., H, W]: strided + block slices when the taps are periodic (no transposes), else gathers.""" + period = self._period(i0, i1, w, p.shape[axis]) + if period is None: + wb = w.astype(np.float64) if axis == -1 else w.astype(np.float64)[:, None] + return self._lerp(np.take(p, i0, axis=axis), np.take(p, i1, axis=axis), wb) + p_in, p_out = period + nb = p.shape[axis] // p_in + taps0 = [int(t) for t in i0[:p_out]] + run = taps0 == list(range(taps0[0], taps0[0] + p_out)) # x0.8: taps (0..3) and (1..4) of 5 + wj = np.asarray(w[:p_out], np.float64) + if axis == -1: + blk = p.reshape(p.shape[:-1] + (nb, p_in)) # [..., H, nb, p_in] (a view) + if run: + a = taps0[0] + res = self._lerp(blk[..., a:a + p_out], np.array(blk[..., a + 1:a + 1 + p_out]), wj) + else: + res = np.empty(p.shape[:-1] + (nb, p_out), F32) + for j in range(p_out): + self._lerp(blk[..., taps0[j]], np.array(blk[..., taps0[j] + 1]), wj[j], out=res[..., j]) + return res.reshape(p.shape[:-1] + (nb * p_out,)) + blk = p.reshape(p.shape[:-2] + (nb, p_in, p.shape[-1])) # [..., nb, p_in, W] (a view) + if run: + a = taps0[0] + res = self._lerp(blk[..., a:a + p_out, :], np.array(blk[..., a + 1:a + 1 + p_out, :]), wj[:, None]) + else: + res = np.empty(p.shape[:-2] + (nb, p_out, p.shape[-1]), F32) + for j in range(p_out): + self._lerp(blk[..., taps0[j], :], np.array(blk[..., taps0[j] + 1, :]), wj[j], out=res[..., j, :]) + return res.reshape(p.shape[:-2] + (nb * p_out, p.shape[-1])) + + def apply_planes(self, planes: np.ndarray, *, out: Optional[np.ndarray] = None) -> np.ndarray: + """Planar float32 ``[..., src_h, src_w]`` -> ``[..., dst_h, dst_w]`` (horizontal pass first, as OpenCV).""" + p = np.ascontiguousarray(planes) + if p.dtype != F32 or tuple(p.shape[-2:]) != self.src_hw: + raise ValueError(f"expected float32 planes [..., {self.src_hw[0]}, {self.src_hw[1]}], got {p.dtype} " + f"{p.shape}") + shape = p.shape[:-2] + tuple(self.dst_hw) + if out is not None and (out.shape != shape or out.dtype != F32): + raise ValueError(f"out must be float32 {shape}, got {out.dtype} {out.shape}") + h = self._pass(p, -1, self.cols0, self.cols1, self.wx) # [..., src_h, dst_w] + v = self._pass(h, -2, self.rows0, self.rows1, self.wy) # [..., dst_h, dst_w] + if out is None: + return v + out[...] = v + return out + + def apply(self, image: np.ndarray, *, out: Optional[np.ndarray] = None) -> np.ndarray: + """``(src_h, src_w[, C])`` float32 -> ``(dst_h, dst_w[, C])`` float32 (horizontal pass first, as OpenCV).""" + img = np.asarray(image) + if img.dtype != F32 or tuple(img.shape[:2]) != self.src_hw: + raise ValueError(f"expected a float32 {self.src_hw} image, got {img.dtype} {img.shape}") + planes = np.moveaxis(img, (0, 1), (-2, -1)) # [C..., H, W] + res = np.moveaxis(self.apply_planes(planes), (-2, -1), (0, 1)) + if out is None: + return np.ascontiguousarray(res) + if out.shape != res.shape or out.dtype != F32: + raise ValueError(f"out must be float32 {res.shape}, got {out.dtype} {out.shape}") + out[...] = res + return out + + +def _linear_axis(n_src: int, n_dst: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """``resize.cpp`` INTER_LINEAR coefficients of one axis: (first tap, second tap, float32 weight of the second).""" + scale = 1.0 / (float(n_dst) / float(n_src)) # inv_scale = (double)dst / src; 1. / inv_scale + f = ((np.arange(n_dst, dtype=np.float64) + 0.5) * scale - 0.5).astype(F32) + s = np.floor(f).astype(np.int64) + w = (f - s.astype(F32)).astype(F32) + low = s < 0 + s[low], w[low] = 0, F32(0) + high = s >= n_src - 1 + s[high], w[high] = n_src - 1, F32(0) + return s, np.minimum(s + 1, n_src - 1), w + + +def _eighths(w: np.ndarray) -> bool: + x = np.asarray(w, np.float64) * 8.0 + return bool(np.all(x == np.round(x))) + + +_LINEAR_LUTS = LUTCache(maxsize=8) + + +def opencv_linear_lut(src_hw: Tuple[int, int], dst_hw: Tuple[int, int], *, strict: bool = True) -> LinearResizeLUT: + """The (cached) float INTER_LINEAR tables for one size pair. + + Verified bit-exact against OpenCV 4.8.1 / 4.11.0 for every x0.8 down-scale (1600x900 -> 1280x720, the deployed + one; 1920x1080, 160x90, 80x45), whose weights are multiples of 1/8. OpenCV computes the coefficients of other + scales differently (up-scales and non-dyadic down-scales differ by up to ~1e-4 relative), so ``strict=True`` + refuses a geometry whose weights are not multiples of 1/8; ``strict=False`` gives the textbook coefficients for + those (an approximation, not an emulation). Exact 2x down-scales are always refused: OpenCV switches + INTER_LINEAR to INTER_AREA there (``resize.cpp``).""" + src_h, src_w = int(src_hw[0]), int(src_hw[1]) + dst_h, dst_w = int(dst_hw[0]), int(dst_hw[1]) + if min(src_h, src_w, dst_h, dst_w) < 1: + raise ValueError(f"empty resize {src_hw} -> {dst_hw}") + if src_h == 2 * dst_h and src_w == 2 * dst_w: + raise ValueError("an exact 2x down-scale runs OpenCV's INTER_AREA path, which is not emulated") + + def make() -> LinearResizeLUT: + r0, r1, wy = _linear_axis(src_h, dst_h) + c0, c1, wx = _linear_axis(src_w, dst_w) + return LinearResizeLUT((src_h, src_w), (dst_h, dst_w), r0, r1, wy, c0, c1, wx) + + lut = _LINEAR_LUTS.get(("linear_f32", src_h, src_w, dst_h, dst_w), make) + if strict and not (_eighths(lut.wx) and _eighths(lut.wy)): + raise ValueError(f"{src_hw} -> {dst_hw} is not a geometry this emulation reproduces bit for bit (weights must " + "be multiples of 1/8, e.g. a x0.8 down-scale); pass strict=False for an approximation") + return lut + + +def opencv_resize_linear_f32(image: np.ndarray, dst_hw: Tuple[int, int], *, strict: bool = True) -> np.ndarray: + """``cv2.resize(image, (dst_w, dst_h))`` (INTER_LINEAR) of a float32 ``(H, W[, C])`` image: bit-exact for the + geometries :func:`opencv_linear_lut` accepts with ``strict=True``.""" + img = np.asarray(image) + return opencv_linear_lut(img.shape[:2], dst_hw, strict=strict).apply(img) + + +def bevformer_input_geometry(src_hw: Tuple[int, int] = (900, 1600), scale: float = 0.8, + pad_divisor: int = 32) -> Dict[str, Tuple[int, int]]: + """Sizes of the node's pipeline for one source size: ``resized_hw`` = ``(int)(src * scale)`` in float32 + (``augmentation_transforms.cpp:104-105``) and ``padded_hw`` (``PadMultiViewImages``, size divisor). Deployed: + (900, 1600) -> (720, 1280) -> (736, 1280); the network normalises its UV by the padded size.""" + s = F32(scale) + h = int(F32(F32(int(src_hw[0])) * s)) + w = int(F32(F32(int(src_hw[1])) * s)) + d = int(pad_divisor) + if d < 1: + raise ValueError("pad_divisor must be >= 1") + return {"src_hw": (int(src_hw[0]), int(src_hw[1])), "resized_hw": (h, w), + "padded_hw": ((h + d - 1) // d * d, (w + d - 1) // d * d)} + + +def _normalize_planes(image: np.ndarray, mean: Any, std: Any) -> np.ndarray: + """BGR uint8 ``(H, W, 3)`` -> float32 planes ``(3, H, W)`` of ``(x - mean_c) / std_c`` as OpenCV evaluates it: + ``convertTo`` with float ``alpha = 1/std``, ``beta = -mean/std`` and one fused multiply-add (exact in float64: + an 8-bit value times a 24-bit alpha plus beta); for alpha == 1 that is the float addition ``x + beta``.""" + img = np.asarray(image) + if img.ndim != 3 or img.shape[2] != 3 or img.dtype != np.uint8: + raise ValueError(f"expected a uint8 (H, W, 3) BGR image, got {img.dtype} {img.shape}") + m = np.asarray(mean, np.float64).reshape(3) + sd = np.asarray(std, np.float64).reshape(3) + alpha = (1.0 / sd).astype(F32) + beta = (-m / sd).astype(F32) + planes = img.transpose(2, 0, 1).astype(F32) # exact: integers 0..255 + for c in range(3): + if alpha[c] == 1.0: + planes[c] += beta[c] # float32, one rounding + else: + planes[c] = planes[c].astype(np.float64) * float(alpha[c]) + float(beta[c]) + return planes + + +def bevformer_normalize(image: np.ndarray, mean: Any = BEVFORMER_MEAN_BGR, std: Any = BEVFORMER_STD) -> np.ndarray: + """One BGR uint8 ``(H, W, 3)`` image -> ``(x - mean_c) / std_c`` as float32 ``(H, W, 3)``, as OpenCV evaluates it + (``convertTo`` with float ``alpha = 1/std``, ``beta = -mean/std``, one fused multiply-add; std 1 deployed).""" + return np.ascontiguousarray(_normalize_planes(image, mean, std).transpose(1, 2, 0)) + + +def bevformer_preprocess(images: Any, *, mean: Any = BEVFORMER_MEAN_BGR, std: Any = BEVFORMER_STD, + scale: float = 0.8, pad_divisor: int = 32, out: Optional[np.ndarray] = None, + workers: int = 1) -> np.ndarray: + """N BGR uint8 camera images (a sequence of ``(H, W, 3)`` or an array ``[N, H, W, 3]``, one source size; the node + feeds 1600x900 after its own ``cv::resize``) -> the network input ``[N, 3, Hp, Wp]`` float32: normalise, resize + x``scale`` (OpenCV float INTER_LINEAR), zero-pad bottom / right to ``pad_divisor``, CHW (B, G, R planes, as + ``to_rgb`` is false). Deployed: ``[6, 3, 736, 1280]`` (the ONNX input ``image`` is this with a leading 1). + ``workers`` > 1 processes the cameras in that many threads (numpy releases the GIL in its loops; about 70 ms per + 1600x900 camera single-threaded on the shared host).""" + imgs = [np.asarray(im) for im in images] + if not imgs: + raise ValueError("no images") + hw = tuple(imgs[0].shape[:2]) + if any(tuple(im.shape[:2]) != hw for im in imgs): + raise ValueError("every camera image must have the same size (the node resizes them to 1600x900 first)") + geo = bevformer_input_geometry(hw, scale, pad_divisor) + (rh, rw), (ph, pw) = geo["resized_hw"], geo["padded_hw"] + lut = opencv_linear_lut(hw, (rh, rw)) # strict: the verified x0.8 geometries + shape = (len(imgs), 3, ph, pw) + if out is None: + out = np.zeros(shape, F32) + else: + if out.shape != shape or out.dtype != F32: + raise ValueError(f"out must be float32 {shape}, got {out.dtype} {out.shape}") + out[:, :, rh:, :] = 0.0 + out[:, :, :, rw:] = 0.0 + def one(i: int) -> None: + lut.apply_planes(_normalize_planes(imgs[i], mean, std), out=out[i, :, :rh, :rw]) + + if int(workers) > 1 and len(imgs) > 1: + from concurrent.futures import ThreadPoolExecutor + + with ThreadPoolExecutor(max_workers=min(int(workers), len(imgs))) as pool: + list(pool.map(one, range(len(imgs)))) + else: + for i in range(len(imgs)): + one(i) + return out + + +# name -> (function, one-line description): the presets this module implements +PRESETS: Dict[str, Tuple[Callable[..., Any], str]] = { + "yolox_letterbox": (yolox_letterbox, "autoware_tensorrt_yolox preprocess.cu:43-129 letterbox (pad 114, BGR)"), + "bevdet_nearest_crop": (bevdet_nearest_crop, "bevdet::Preprocess nearest resize 0.44 + crop (140, 0) of the " + "1600x900 image -> B, G, R uint8 planes"), + "bevformer_preprocess": (bevformer_preprocess, "autoware_tensorrt_bevformer normalise (BGR mean, std 1) -> " + "cv::resize x0.8 INTER_LINEAR on float -> zero pad to /32, CHW"), +} diff --git a/code/tt_depthpro2/ttaw/image_area.py b/code/tt_depthpro2/ttaw/image_area.py new file mode 100644 index 0000000000000000000000000000000000000000..a3e8385ae18e0a1bf7b9cdea0ddce4b660555a14 --- /dev/null +++ b/code/tt_depthpro2/ttaw/image_area.py @@ -0,0 +1,179 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C14 image pre-processing, METEOR preset: a bit-exact host emulation of OpenCV's ``cv::resize(..., INTER_AREA)`` on +uint8 images (down-scaling), driven by cached per-size tables. numpy only; no ttnn, no torch, no OpenCV. + +METEOR's runtimes feed every camera as RGB uint8 768x432 and resize larger frames with ``cv2.resize(img, (768, 432), +interpolation=cv2.INTER_AREA)`` (tier4/METEOR ``hf/onnx_smoke_test.py:42-44``; the training extraction +``bevlane/extract_gt.py:114-130`` resized the raw, unrectified JPEGs the same way; research/meteor/SPEC.md section 3), +anisotropically when the aspect ratio differs (2880x1860 -> 768x432). :func:`meteor_resize` reproduces it; the +intrinsics follow with :func:`scale_intrinsics` (row 0 x 768 / w0, row 1 x 432 / h0, ``extract_gt.py:128-130``). + +What OpenCV computes (``modules/imgproc/src/resize.cpp``, identical in 4.8.1 and 4.11.0; the IPP path declines +INTER_AREA because it is not bit-exact, ``ipp_resize``: ``ippSuper`` needs ``useIPP_NotExact``): + +- ``inv_scale = (double)dst / src`` per axis, ``scale = 1.0 / inv_scale`` (double). +- **Integer factors** (``|scale - (int)scale| < DBL_EPSILON`` on both axes; ``resizeAreaFast_``): every output pixel is + the integer sum ``s`` of its ``fx * fy`` source pixels, then ``saturate_cast(s * (1.f / area))``: one float32 + product, rounded half to even (``cvRound``). Exception, the 2x2 ``fast_mode`` of ``ResizeAreaFastVec`` for 1-, 3- + and 4-channel images: ``(s + 2) >> 2`` (half up). Measured on both OpenCV builds (2-channel images take the float + path; 3x3 and 5x5 factors the float path). +- **Other factors** (``resizeArea_``): ``computeResizeAreaTab`` lists, per output column (and row), the + covered source pixels with float32 weights computed in double (``(sx1 - fsx1) / cellWidth``, ``1.0 / cellWidth``, + ``min(min(fsx2 - sx2, 1), cellWidth) / cellWidth``; partial pixels below 1e-3 skipped). Each source row is first + reduced horizontally, ``buf[dx] += S[sx] * alpha`` in table order (float32 multiply, then float32 add: no FMA, the + generic code is compiled for the SSE baseline), then the rows are combined, ``sum[dx] += beta * buf[dx]`` in table + order, and ``saturate_cast(sum)`` rounds half to even and clamps to [0, 255]. + +The emulation replays exactly these float32 operations in the same order, vectorised over the image (zero-weight +padding of the per-pixel tap lists adds exact zeros). Verified against cv2 4.8.1 (tt-env) and 4.11.0 (research venv) +on random and real images of many sizes (``common/tests/host/test_image_area_host.py``): 0 mismatches. +Up-scaling (any axis with ``src < dst``) runs a different OpenCV path (linear-like fixed-point coefficients) and is +refused: METEOR's cameras are all larger than 768x432. +""" +from __future__ import annotations + +import sys +from dataclasses import dataclass +from typing import Any, Optional, Tuple + +import numpy as np + +from .image import LUTCache + +__all__ = ["AreaResizeLUT", "opencv_area_lut", "opencv_resize_area_u8", "meteor_resize", "scale_intrinsics", + "METEOR_INPUT_HW"] + +F32 = np.float32 +METEOR_INPUT_HW = (432, 768) # every METEOR camera slot (meteor_v157.param.yaml:11-12) +_DBL_EPSILON = sys.float_info.epsilon + + +def _area_axis(n_src: int, n_dst: int, scale: float) -> Tuple[np.ndarray, np.ndarray]: + """``computeResizeAreaTab`` of one axis as padded per-output tap lists: (src index [n_dst, T], weight [n_dst, T]) + in table order; unused taps have weight 0 and index 0.""" + taps = [] + for dx in range(n_dst): + fsx1 = dx * scale + fsx2 = fsx1 + scale + cell = min(scale, n_src - fsx1) + sx1 = int(np.ceil(fsx1)) + sx2 = int(np.floor(fsx2)) + sx2 = min(sx2, n_src - 1) + sx1 = min(sx1, sx2) + row = [] + if sx1 - fsx1 > 1e-3: + row.append((sx1 - 1, F32((sx1 - fsx1) / cell))) + for sx in range(sx1, sx2): + row.append((sx, F32(1.0 / cell))) + if fsx2 - sx2 > 1e-3: + row.append((sx2, F32(min(min(fsx2 - sx2, 1.0), cell) / cell))) + taps.append(row) + width = max(len(r) for r in taps) + idx = np.zeros((n_dst, width), np.int64) + w = np.zeros((n_dst, width), F32) + for i, row in enumerate(taps): + for k, (s, a) in enumerate(row): + idx[i, k] = s + w[i, k] = a + return idx, w + + +@dataclass(frozen=True) +class AreaResizeLUT: + """The cached tables of one (source size, destination size) pair; :meth:`apply` resizes one uint8 image.""" + + src_hw: Tuple[int, int] + dst_hw: Tuple[int, int] + fast: Optional[Tuple[int, int]] # integer factors (fy, fx) of the resizeAreaFast_ path, else None + rows: Optional[np.ndarray] # [dst_h, Ty] source rows (general path) + row_w: Optional[np.ndarray] # [dst_h, Ty] float32 beta + cols: Optional[np.ndarray] # [dst_w, Tx] source columns + col_w: Optional[np.ndarray] # [dst_w, Tx] float32 alpha + + def apply(self, image: np.ndarray, *, out: Optional[np.ndarray] = None) -> np.ndarray: + img = np.asarray(image) + if img.dtype != np.uint8 or img.ndim not in (2, 3) or tuple(img.shape[:2]) != self.src_hw: + raise ValueError(f"expected a uint8 {self.src_hw} image (HxW or HxWxC), got {img.dtype} {img.shape}") + squeeze = img.ndim == 2 + x = img[:, :, None] if squeeze else img + dh, dw = self.dst_hw + if self.fast is not None: + fy, fx = self.fast + s = x[:dh * fy, :dw * fx].astype(np.int64).reshape(dh, fy, dw, fx, x.shape[2]).sum(axis=(1, 3)) + if (fy, fx) == (2, 2) and x.shape[2] in (1, 3, 4): + res = (s + 2) >> 2 # ResizeAreaFastVec fast_mode: half up + else: + res = np.rint(s.astype(F32) * F32(1.0 / (fx * fy))) # float32 product, half to even + else: + # horizontal pass per source row: buf[dx] = sum_k S[cols[dx, k]] * col_w[dx, k] (float32, table order) + buf = np.zeros((x.shape[0], dw, x.shape[2]), F32) + src = x.astype(F32) + for k in range(self.cols.shape[1]): + buf += src[:, self.cols[:, k], :] * self.col_w[None, :, k, None] + # vertical pass: sum[dy] = sum_j beta[dy, j] * buf[rows[dy, j]] (float32, table order) + acc = np.zeros((dh, dw, x.shape[2]), F32) + for j in range(self.rows.shape[1]): + acc += self.row_w[:, j, None, None] * buf[self.rows[:, j]] + res = np.rint(acc) # cvRound: half to even + res = np.clip(res, 0, 255).astype(np.uint8) + if squeeze: + res = res[:, :, 0] + if out is not None: + out[...] = res + return out + return res + + +_AREA_LUTS = LUTCache(maxsize=16) # 8 cameras of up to two sizes each + + +def opencv_area_lut(src_hw: Tuple[int, int], dst_hw: Tuple[int, int]) -> AreaResizeLUT: + """Tables of ``cv::resize(INTER_AREA)`` from ``src_hw`` down to ``dst_hw`` (cached per size pair).""" + src_hw = (int(src_hw[0]), int(src_hw[1])) + dst_hw = (int(dst_hw[0]), int(dst_hw[1])) + return _AREA_LUTS.get((src_hw, dst_hw), lambda: _build_area_lut(src_hw, dst_hw)) + + +def _build_area_lut(src_hw: Tuple[int, int], dst_hw: Tuple[int, int]) -> AreaResizeLUT: + (sh, sw), (dh, dw) = src_hw, dst_hw + if min(sh, sw, dh, dw) < 1: + raise ValueError(f"bad sizes {src_hw} -> {dst_hw}") + if dh > sh or dw > sw: + raise ValueError(f"INTER_AREA up-scaling {src_hw} -> {dst_hw} is not emulated (OpenCV uses another path)") + scale_y = 1.0 / (float(dh) / sh) + scale_x = 1.0 / (float(dw) / sw) + iy, ix = int(round(scale_y)), int(round(scale_x)) + if abs(scale_x - ix) < _DBL_EPSILON and abs(scale_y - iy) < _DBL_EPSILON: + return AreaResizeLUT(src_hw, dst_hw, (iy, ix), None, None, None, None) + rows, row_w = _area_axis(sh, dh, scale_y) + cols, col_w = _area_axis(sw, dw, scale_x) + return AreaResizeLUT(src_hw, dst_hw, None, rows, row_w, cols, col_w) + + +def opencv_resize_area_u8(image: np.ndarray, dst_hw: Tuple[int, int], *, + out: Optional[np.ndarray] = None) -> np.ndarray: + """``cv2.resize(image, (dst_w, dst_h), interpolation=cv2.INTER_AREA)`` for uint8 HxW / HxWxC down-scaling; + the same size returns a copy (OpenCV's ``copyTo`` shortcut).""" + img = np.asarray(image) + if tuple(img.shape[:2]) == tuple(dst_hw): + res = np.array(img, dtype=np.uint8, copy=True) + if out is not None: + out[...] = res + return out + return res + return opencv_area_lut(img.shape[:2], dst_hw).apply(img, out=out) + + +def meteor_resize(image: np.ndarray, *, out: Optional[np.ndarray] = None) -> np.ndarray: + """One camera frame (uint8 HxWx3, any channel order: the resize is per channel) -> 432x768 as METEOR's runtimes + (``INTER_AREA`` when the size differs, a copy otherwise).""" + return opencv_resize_area_u8(image, METEOR_INPUT_HW, out=out) + + +def scale_intrinsics(K: Any, src_hw: Tuple[int, int], dst_hw: Tuple[int, int] = METEOR_INPUT_HW) -> np.ndarray: + """K of a ``src_hw`` image -> K of the resized ``dst_hw`` image: row 0 x dst_w / src_w, row 1 x dst_h / src_h + (``extract_gt.py:128-130``; skew is scaled with row 0 and ignored by the network). float64.""" + k = np.array(K, dtype=np.float64).reshape(3, 3).copy() + k[0] *= dst_hw[1] / float(src_hw[1]) + k[1] *= dst_hw[0] / float(src_hw[0]) + return k diff --git a/code/tt_depthpro2/ttaw/image_linear.py b/code/tt_depthpro2/ttaw/image_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..d31a987cd97b797f19977aba4e3c4e95a0e6143e --- /dev/null +++ b/code/tt_depthpro2/ttaw/image_linear.py @@ -0,0 +1,292 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C14 image pre-processing, SceneSeg preset: bit-exact host emulations of OpenCV's ``cv::resize`` on uint8 images +with ``INTER_LINEAR`` (the default interpolation) and ``INTER_NEAREST``, driven by cached per-size tables, and the +pre-processing of Autoware VisionPilot's SceneSeg node built on them. numpy only; no ttnn, no torch, no OpenCV. + +The SceneSeg node (VisionPilot ``middleware_recipes/common/backends/onnx_runtime_backend.cpp:41-60`` and the identical +``tensorrt_backend.cpp:160-177`` at autowarefoundation/vision_pilot ``04fa3e80``; research/sceneseg/SPEC.md section 3) +takes the ``bgr8`` image of ``cv_bridge``, then:: + + cv::resize(input_image, resized_image, cv::Size(640, 320)); // INTER_LINEAR, aspect ratio not kept + resized_image.convertTo(float_image, CV_32FC3, 1.0 / 255.0); + cv::subtract(float_image, cv::Scalar(0.406, 0.456, 0.485), float_image); + cv::divide(float_image, cv::Scalar(0.225, 0.224, 0.229), float_image); + cv::split(float_image, channels); // planes B, G, R -> NCHW + +and publishes the argmax mask resized back to the source size with ``cv::resize(..., INTER_NEAREST)`` +(``run_model_node.cpp:117-188``). :func:`sceneseg_resize` / :func:`sceneseg_normalize` / :func:`sceneseg_preprocess` +reproduce the first part, :func:`opencv_resize_nearest` the mask resize. + +What OpenCV computes (``modules/imgproc/src/resize.cpp`` and ``core/src/arithm.cpp``; identical in 4.8.1 and 4.11.0 +on this x86-64 host, measured; the IPP path declines both resizes: uint8 ``ippLinear`` and ``ippNearest`` need +``useIPP_NotExact``): + +- ``cv::resize`` with ``dsize == ssize`` copies. ``inv_scale = (double)dst / src`` and ``scale = 1.0 / inv_scale`` + per axis. +- **INTER_LINEAR, exactly 2x down on both axes**: OpenCV switches to ``INTER_AREA`` (``resizeAreaFast_``), which + :func:`.image_area.opencv_resize_area_u8` emulates (2x2 ``fast_mode``: ``(s + 2) >> 2``). +- **INTER_LINEAR otherwise** (``resizeGeneric_`` with ``HResizeLinear`` and the uchar + specialisation of ``VResizeLinear``): per output column ``fx = (float)((dx + 0.5) * scale - 0.5)``, + ``sx = floor(fx)``, ``fx -= sx`` (float); at the borders ``sx < 0 -> sx = 0, fx = 0`` and ``sx >= W - 1 -> + sx = W - 1, fx = 0``; integer weights ``a0 = cvRound((1.f - fx) * 2048)``, ``a1 = cvRound(fx * 2048)`` (round half + to even). Rows take the same coefficients **without** the border fix (the row indices are clipped to [0, H - 1] + instead, ``clip(sy + k, 0, H)``). The horizontal pass is exact integer arithmetic, + ``h = S[sx] * a0 + S[sx + 1] * a1`` (int32), and the vertical pass is the fixed-point + ``(((b0 * (h0 >> 4)) >> 16) + ((b1 * (h1 >> 4)) >> 16) + 2) >> 2`` that the SIMD and the scalar code share. +- **INTER_NEAREST** (``resizeNN``): ``sx = min(floor(dx * (1.0 / inv_scale_x)), W - 1)`` in double, rows alike. +- **Normalisation**: ``convertTo(CV_32F, 1/255)`` is one float32 product ``x * (float)(1/255)``; ``cv::subtract`` + with a ``Scalar`` runs in float32 (``x - (float)mean_c``); ``cv::divide`` with a ``Scalar`` runs in double and + rounds once to float32 (``(float)((double)x / std_c)``), measured with OpenCV's own scalar arithmetic. A float32 + division instead differs by one ulp in about 27 % of the values (the research reference's arithmetic). + +Channel orders (SPEC section 3, PLAN.md D10): ``"bgr"`` is the deployed path: B, G, R planes normalised with the +BGR-ordered ImageNet constants, fed to a network trained on R, G, B. ``"rgb"`` is the training-consistent option: the +same arithmetic on R, G, B planes with the RGB constants (an exact channel permutation of the image first, as a +``cv_bridge`` ``rgb8`` conversion would give). Every physical colour gets the same mean and std in both orders, so +the two inputs are channel permutations of each other. + +Verified bit-exact against cv2 4.8.1 (tt-env) and 4.11.0 (research venv) on random and real images of many sizes +(down- and up-scaling, odd sizes, 1-4 channels), against a scalar transliteration of ``resize.cpp``, and against the +research golden inputs of the SceneSeg port (``common/tests/host/test_image_sceneseg_host.py``). +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Optional, Tuple + +import numpy as np + +from .image import LUTCache +from .image_area import opencv_resize_area_u8 + +__all__ = [ + "LinearResizeU8LUT", + "opencv_linear_u8_lut", + "opencv_resize_linear_u8", + "NearestResizeLUT", + "opencv_nearest_lut", + "opencv_resize_nearest", + "sceneseg_resize", + "sceneseg_normalize", + "sceneseg_preprocess", + "SCENESEG_INPUT_HW", + "SCENESEG_MEAN_RGB", + "SCENESEG_STD_RGB", + "SCENESEG_CHANNEL_ORDERS", +] + +F32 = np.float32 +INTER_RESIZE_COEF_SCALE = 2048 # 1 << INTER_RESIZE_COEF_BITS (11), resize.cpp +SCENESEG_INPUT_HW = (320, 640) # (H, W) of the ONNX input; fixed by the SceneContext reshape (SPEC 4.2) +SCENESEG_MEAN_RGB = (0.485, 0.456, 0.406) # ImageNet, R G B (the C++ code lists them reversed for B G R planes) +SCENESEG_STD_RGB = (0.229, 0.224, 0.225) +SCENESEG_CHANNEL_ORDERS = ("bgr", "rgb") + + +def _check_hw(hw: Tuple[int, int], what: str) -> Tuple[int, int]: + h, w = (int(v) for v in hw) + if h < 1 or w < 1: + raise ValueError(f"{what} must be positive, got {hw}") + return h, w + + +def _as_image(image: Any, dtype: Optional[type] = np.uint8) -> np.ndarray: + a = np.asarray(image) + if a.ndim not in (2, 3) or a.shape[0] < 1 or a.shape[1] < 1: + raise ValueError(f"expected an HxW or HxWxC image, got shape {a.shape}") + if dtype is not None and a.dtype != dtype: + raise ValueError(f"expected {np.dtype(dtype).name} data, got {a.dtype}") + return a + + +# ----------------------------------------------------------------------------------------------- INTER_LINEAR + +def _linear_axis(n_src: int, n_dst: int, border_fix: bool) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """One axis of ``resize()``'s INTER_LINEAR tables for uint8: source indices (clipped) and integer weights.""" + scale = 1.0 / (n_dst / n_src) # scale = 1. / inv_scale, inv = (double)dst / src + f = ((np.arange(n_dst, dtype=np.float64) + 0.5) * scale - 0.5).astype(F32) + s = np.floor(f).astype(np.int64) # cvFloor(fx) + f = (f - s.astype(F32)).astype(F32) # fx -= sx (float; exact) + if border_fix: # x axis only (the y loop has no such fix) + lo = s < 0 + f[lo], s[lo] = F32(0), 0 + hi = s >= n_src - 1 + f[hi], s[hi] = F32(0), n_src - 1 + one = F32(INTER_RESIZE_COEF_SCALE) + w0 = np.rint((F32(1) - f).astype(F32) * one).astype(np.int32) # saturate_cast(cbuf[k] * 2048): cvRound + w1 = np.rint(f * one).astype(np.int32) + return np.clip(s, 0, n_src - 1), np.clip(s + 1, 0, n_src - 1), w0, w1 + + +@dataclass(frozen=True) +class LinearResizeU8LUT: + """The tables of one ``cv::resize(uint8, INTER_LINEAR)`` geometry. ``mode``: ``"copy"`` (same size), + ``"area2x"`` (exact 2x down on both axes: OpenCV's INTER_AREA fast path) or ``"linear"``.""" + + src_hw: Tuple[int, int] + dst_hw: Tuple[int, int] + mode: str + cols0: Optional[np.ndarray] = None # (w,) source column of the first tap (clipped) + cols1: Optional[np.ndarray] = None # (w,) second tap + a0: Optional[np.ndarray] = None # (w,) int32 weights, a0 + a1 == 2048 up to OpenCV's rounding + a1: Optional[np.ndarray] = None + rows: Optional[np.ndarray] = None # (R,) the source rows the vertical pass reads (sorted, unique) + r0: Optional[np.ndarray] = None # (h,) index into ``rows`` of the first row tap + r1: Optional[np.ndarray] = None # (h,) second row tap + b0: Optional[np.ndarray] = None # (h,) int32 row weights + b1: Optional[np.ndarray] = None + + def apply(self, image: Any, *, out: Optional[np.ndarray] = None) -> np.ndarray: + """Resize one HxW or HxWxC uint8 image of size ``src_hw`` -> ``dst_hw`` (same channel count).""" + img = _as_image(image) + if img.shape[:2] != self.src_hw: + raise ValueError(f"table built for {self.src_hw}, image is {img.shape[:2]}") + if self.mode == "copy": + res = img.copy() + elif self.mode == "area2x": + res = opencv_resize_area_u8(img, self.dst_hw) + else: + src = img if img.ndim == 3 else img[:, :, None] + sub = src[self.rows] # only the rows the vertical pass reads + h = sub[:, self.cols0, :].astype(np.int32) # horizontal pass, exact int32 (<= 255 * 2048) + h *= self.a0[None, :, None] + h1 = sub[:, self.cols1, :].astype(np.int32) + h1 *= self.a1[None, :, None] + h += h1 + h >>= 4 # S[x] >> 4 (h >= 0) + v = h[self.r0] # vertical pass, the uchar VResizeLinear + v *= self.b0[:, None, None] + v >>= 16 + v1 = h[self.r1] + v1 *= self.b1[:, None, None] + v1 >>= 16 + v += v1 + v += 2 + v >>= 2 + res = v.astype(np.uint8) # in [0, 255] (weights sum to 2048) + if img.ndim == 2: + res = res[:, :, 0] + if out is not None: + out[...] = res + return out + return res + + +def _build_linear_lut(src_hw: Tuple[int, int], dst_hw: Tuple[int, int]) -> LinearResizeU8LUT: + (H, W), (h, w) = src_hw, dst_hw + if (h, w) == (H, W): + return LinearResizeU8LUT(src_hw, dst_hw, "copy") + if 2 * h == H and 2 * w == W: # is_area_fast && iscale_x == iscale_y == 2 + return LinearResizeU8LUT(src_hw, dst_hw, "area2x") + c0, c1, a0, a1 = _linear_axis(W, w, True) + y0, y1, b0, b1 = _linear_axis(H, h, False) + rows = np.unique(np.concatenate([y0, y1])) + r0, r1 = np.searchsorted(rows, y0), np.searchsorted(rows, y1) + return LinearResizeU8LUT(src_hw, dst_hw, "linear", c0, c1, a0, a1, rows, r0, r1, b0, b1) + + +_LINEAR_U8_LUTS = LUTCache(maxsize=8) + + +def opencv_linear_u8_lut(src_hw: Tuple[int, int], dst_hw: Tuple[int, int]) -> LinearResizeU8LUT: + """The cached tables of ``cv::resize(uint8 src_hw -> dst_hw, INTER_LINEAR)`` (any scale, up or down).""" + key = (_check_hw(src_hw, "src_hw"), _check_hw(dst_hw, "dst_hw")) + return _LINEAR_U8_LUTS.get(key, lambda: _build_linear_lut(*key)) + + +def opencv_resize_linear_u8(image: Any, dst_hw: Tuple[int, int], *, out: Optional[np.ndarray] = None) -> np.ndarray: + """``cv::resize(image, dst, Size(w, h))`` (INTER_LINEAR) of an HxW or HxWxC uint8 image, bit-exact.""" + img = _as_image(image) + return opencv_linear_u8_lut(img.shape[:2], dst_hw).apply(img, out=out) + + +# ---------------------------------------------------------------------------------------------- INTER_NEAREST + +@dataclass(frozen=True) +class NearestResizeLUT: + """``resizeNN`` index tables: ``rows`` (h,), ``cols`` (w,); a copy when the sizes are equal.""" + + src_hw: Tuple[int, int] + dst_hw: Tuple[int, int] + rows: np.ndarray + cols: np.ndarray + + def apply(self, image: Any, *, out: Optional[np.ndarray] = None) -> np.ndarray: + """Resize one HxW or HxWxC image of any dtype (a gather: values are copied, never mixed).""" + img = _as_image(image, dtype=None) + if img.shape[:2] != self.src_hw: + raise ValueError(f"table built for {self.src_hw}, image is {img.shape[:2]}") + res = img.copy() if self.src_hw == self.dst_hw else img[self.rows][:, self.cols] + if out is not None: + out[...] = res + return out + return res + + +def _nearest_axis(n_src: int, n_dst: int) -> np.ndarray: + inv = 1.0 / (n_dst / n_src) # ifx = 1. / fx, fx = inv_scale_x + return np.minimum(np.floor(np.arange(n_dst, dtype=np.float64) * inv).astype(np.int64), n_src - 1) + + +_NEAREST_LUTS = LUTCache(maxsize=8) + + +def opencv_nearest_lut(src_hw: Tuple[int, int], dst_hw: Tuple[int, int]) -> NearestResizeLUT: + """The cached index tables of ``cv::resize(src_hw -> dst_hw, INTER_NEAREST)``.""" + key = (_check_hw(src_hw, "src_hw"), _check_hw(dst_hw, "dst_hw")) + return _NEAREST_LUTS.get(key, lambda: NearestResizeLUT(key[0], key[1], _nearest_axis(key[0][0], key[1][0]), + _nearest_axis(key[0][1], key[1][1]))) + + +def opencv_resize_nearest(image: Any, dst_hw: Tuple[int, int], *, out: Optional[np.ndarray] = None) -> np.ndarray: + """``cv::resize(image, dst, Size(w, h), 0, 0, INTER_NEAREST)`` of an HxW or HxWxC image, bit-exact.""" + img = _as_image(image, dtype=None) + return opencv_nearest_lut(img.shape[:2], dst_hw).apply(img, out=out) + + +# ------------------------------------------------------------------------------------------- SceneSeg preset + +def _order(channel_order: str) -> str: + if channel_order not in SCENESEG_CHANNEL_ORDERS: + raise ValueError(f"channel_order must be one of {SCENESEG_CHANNEL_ORDERS}, got {channel_order!r}") + return channel_order + + +def sceneseg_resize(image_bgr: Any, *, dst_hw: Tuple[int, int] = SCENESEG_INPUT_HW, + out: Optional[np.ndarray] = None) -> np.ndarray: + """The node's squash, ``cv::resize(input_image, resized, Size(640, 320))`` (INTER_LINEAR, aspect ratio not + kept) of one HxWx3 uint8 image (channel order kept: give it B, G, R as ``cv_bridge`` ``bgr8`` does) -> + ``(320, 640, 3)`` uint8. This is the device input of the TT port (614 KB).""" + img = _as_image(image_bgr) + if img.ndim != 3 or img.shape[2] != 3: + raise ValueError(f"expected an HxWx3 BGR image, got shape {img.shape}") + return opencv_resize_linear_u8(img, dst_hw, out=out) + + +def sceneseg_normalize(resized_bgr: Any, *, channel_order: str = "bgr") -> np.ndarray: + """The node's normalisation of the resized B, G, R uint8 image -> the ONNX input ``float32 [1, 3, H, W]``. + + ``"bgr"`` (deployed): planes B, G, R; ``convertTo(CV_32F, 1/255)`` (float32 product), ``cv::subtract`` of + (0.406, 0.456, 0.485) in float32, ``cv::divide`` by (0.225, 0.224, 0.229) in double rounded to float32. + ``"rgb"`` (training order): the same arithmetic on planes R, G, B with (0.485, 0.456, 0.406) / + (0.229, 0.224, 0.225).""" + img = _as_image(resized_bgr) + if img.ndim != 3 or img.shape[2] != 3: + raise ValueError(f"expected an HxWx3 BGR image, got shape {img.shape}") + if _order(channel_order) == "rgb": + img = img[:, :, ::-1] + mean, std = SCENESEG_MEAN_RGB, SCENESEG_STD_RGB + else: + mean, std = SCENESEG_MEAN_RGB[::-1], SCENESEG_STD_RGB[::-1] + planes = np.ascontiguousarray(img.transpose(2, 0, 1)).astype(F32) # cv::split -> NCHW + x = planes * F32(1.0 / 255.0) # convertTo: float32 product + x = x - np.asarray(mean, F32)[:, None, None] # cv::subtract (float32) + x = (x.astype(np.float64) / np.asarray(std, np.float64)[:, None, None]).astype(F32) # cv::divide (double) + return x[None] + + +def sceneseg_preprocess(image_bgr: Any, *, channel_order: str = "bgr") -> np.ndarray: + """One HxWx3 B, G, R uint8 camera image -> the SceneSeg ONNX input ``float32 [1, 3, 320, 640]``, bit-exact with + the deployed C++ (``"bgr"``) or its training-order variant (``"rgb"``): :func:`sceneseg_normalize` of + :func:`sceneseg_resize`.""" + return sceneseg_normalize(sceneseg_resize(image_bgr), channel_order=channel_order) diff --git a/code/tt_depthpro2/ttaw/image_triangle.py b/code/tt_depthpro2/ttaw/image_triangle.py new file mode 100644 index 0000000000000000000000000000000000000000..842525442ba06b48d6909df3bf68f9026c6b9d89 --- /dev/null +++ b/code/tt_depthpro2/ttaw/image_triangle.py @@ -0,0 +1,344 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C14 image pre-processing, StreamPETR preset: a bit-exact host emulation of Autoware's fused anti-aliased resize + +crop + normalise CUDA kernel (a PIL-style triangle filter with adaptive support), driven by cached per-size tables. +numpy only; no ttnn, no torch, no OpenCV. + +Deployed code (autoware_universe main @ 9ceaccf, ``perception/autoware_camera_streampetr``; research/streampetr/SPEC.md +section 3.1): + +- ``calculate_image_processing_params`` (``lib/network/camera_data_store.cpp:287-316``), float32: + ``resize = max(480 / (float)H, 640 / (float)W)``; ``new_w = (int)(W * resize)``, ``new_h = (int)(H * resize)``; + ``crop_h = max(0, (int)(1.0f * new_h) - 480)`` (the top rows are cropped, the bottom kept: ``bottom_crop_portion`` + 0), ``crop_w = max(0, (new_w - 640) / 2)`` (centred) -> :func:`autoware_resize_geometry`. +- ``resize_and_extract_roi_kernel`` (``lib/network/preprocess_kernel.cu:73-176``; the 0.52.1 kernel + ``resizeAndExtractRoi_kernel`` has the same arithmetic), per output pixel, all float32: + ``r = (float)(out + roi_start)``, ``scale = (float)in / (float)resized``, ``centre = (r + 0.5f) * scale - 0.5f``, + ``support = scale > 1 ? scale : 1``, taps ``ceilf(centre - support) .. floorf(centre + support)`` clamped to the + image, ``w = max(0, 1 - |centre - i| / support)`` per axis, ``w = wx * wy``; the loop runs **y outer, x inner** + and skips ``w <= 0``: ``sum_c += pix_c * w``, ``sum_w += w``; then ``sum_c /= sum_w`` (when ``sum_w > 0``) and + ``out_c = (sum_c - mean[c]) / std[c]``, written planar (CHW). The channel order of the output is the byte order + of the buffer the kernel reads: RGB on main (a ``bgr8`` message is swapped in place first, + ``convert_bgr_to_rgb_kernel``), the message order on 0.52.1. + +The emulation replays exactly these float32 operations in the same order, vectorised over the output pixels: per +output row / column the source taps and the 1-D weights are tabulated once (:class:`TriangleResizeLUT`), and the 2-D +accumulation runs tap pair by tap pair in the kernel's (y outer, x inner) order. Taps outside a pixel's window carry +weight 0, which adds exact zeros (the kernel skips them). + +**Floating-point contraction** (``fma``). Written as C, every operation rounds once: ``fma=False`` (default) does +that, and equals the SPEC's numpy port (``research/streampetr/scripts/sp_common.py``) and the research goldens bit +for bit (their ``inputs_sha256.json``). The node's CMakeLists passes no ``--fmad`` / ``--use_fast_math`` flag, so +nvcc compiles with its default ``--fmad=true``, which lets the compiler fuse a multiply feeding an add into one +``fmaf``. ``fma=True`` models LLVM NVPTX's aggressive fusion: ``centre = fmaf(r + 0.5f, scale, -0.5f)``, +``sum_c = fmaf(pix_c, w, sum_c)`` and ``sum_w = fmaf(wx, wy, sum_w)`` (the rounded ``w`` still feeds the channel +products). Which form the deployed binary has cannot be checked without CUDA. The two differ in ~43 % of the +inputs by at most ~3e-5 in normalised units (one ulp of a ~1000 px centre moves every tap weight; measured in +``common/tests/host/test_image_triangle_host.py``), two orders of magnitude below the bf16 rounding of the device +input. + +Normalisation presets (:data:`STREAMPETR_PRESETS`, SPEC section 3.4; PLAN.md D7 picks ``autoware_main``): + +================== ====================== ================================================================== +preset planes (buffer order) statistics +================== ====================== ================================================================== +``autoware_main`` R, G, B mean (123.675, 116.28, 103.53), std (58.395, 57.12, 57.375) + (universe main / 0.53.0, ``camera_data_store.cpp:128-134``) +``autoware_0.52`` R, G, B (an ``rgb8`` mean (103.53, 116.28, 123.675), std (57.375, 57.12, 58.395) on the + camera, as TIER IV's) message bytes (0.52.1, ``camera_data_store.cpp:122-127``) +``awml_training`` B, G, R the 0.52 statistics (AWML t4base v2.5 test pipeline: cv2 decode, + ``to_rgb=False``; = 0.52.1 fed a ``bgr8`` camera) +================== ====================== ================================================================== +""" +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +from typing import Any, Dict, Optional, Sequence, Tuple + +import numpy as np + +from .image import LUTCache + +__all__ = [ + "TriangleGeometry", + "TriangleResizeLUT", + "StreamPETRPreset", + "autoware_resize_geometry", + "triangle_resize_lut", + "fma_f32", + "streampetr_preprocess", + "streampetr_preprocess_batch", + "STREAMPETR_PRESETS", + "STREAMPETR_INPUT_HW", + "STREAMPETR_MEAN_RGB", + "STREAMPETR_STD_RGB", + "STREAMPETR_MEAN_BGR", + "STREAMPETR_STD_BGR", +] + +F32 = np.float32 +F64 = np.float64 +STREAMPETR_INPUT_HW = (480, 640) # HF ml_package_camera_streampetr.param.yaml:7-8 (input_image_height / _width) +# camera_data_store.cpp:128-134 (main: RGB order) and AW052 camera_data_store.cpp:122-127 (0.52.1: BGR order) +STREAMPETR_MEAN_RGB = (123.675, 116.280, 103.530) +STREAMPETR_STD_RGB = (58.395, 57.120, 57.375) +STREAMPETR_MEAN_BGR = (103.530, 116.280, 123.675) +STREAMPETR_STD_BGR = (57.375, 57.120, 58.395) + + +@dataclass(frozen=True) +class StreamPETRPreset: + """One normalisation preset: the plane order the kernel sees (``"rgb"`` or ``"bgr"``) and the per-plane + statistics, as float32 values (the kernel reads them from a float device buffer).""" + + name: str + planes: str + mean: Tuple[float, float, float] + std: Tuple[float, float, float] + description: str = "" + + def mean_f32(self) -> np.ndarray: + return np.asarray(self.mean, dtype=F32) + + def std_f32(self) -> np.ndarray: + return np.asarray(self.std, dtype=F32) + + +STREAMPETR_PRESETS: Dict[str, StreamPETRPreset] = { + "autoware_main": StreamPETRPreset("autoware_main", "rgb", STREAMPETR_MEAN_RGB, STREAMPETR_STD_RGB, + "Autoware universe main / 0.53.0: RGB planes, RGB-ordered statistics"), + "autoware_0.52": StreamPETRPreset("autoware_0.52", "rgb", STREAMPETR_MEAN_BGR, STREAMPETR_STD_BGR, + "Autoware 0.52.1 fed an rgb8 camera: message-order (RGB) planes, " + "BGR-ordered statistics"), + "awml_training": StreamPETRPreset("awml_training", "bgr", STREAMPETR_MEAN_BGR, STREAMPETR_STD_BGR, + "AWML t4base v2.5 training / test pipeline (= 0.52.1 fed a bgr8 camera): " + "BGR planes, BGR statistics"), +} + + +# --------------------------------------------------------------------------------------------- geometry + + +@dataclass(frozen=True) +class TriangleGeometry: + """``calculate_image_processing_params`` of one source size: the virtual resized image and the ROI cut from it.""" + + src_hw: Tuple[int, int] + resized_hw: Tuple[int, int] # (new_h, new_w) + roi_hw: Tuple[int, int] # the network input (480, 640) + roi_start: Tuple[int, int] # (start_y, start_x) in the resized image + resize: float # the float32 resize factor, as an exact Python float + + @property + def resize_f32(self) -> np.float32: + return F32(self.resize) + + def to_dict(self) -> Dict[str, Any]: + return {"src_hw": list(self.src_hw), "resized_hw": list(self.resized_hw), "roi_hw": list(self.roi_hw), + "roi_start": list(self.roi_start), "resize": self.resize} + + +def autoware_resize_geometry(src_h: int, src_w: int, dst_h: int = STREAMPETR_INPUT_HW[0], + dst_w: int = STREAMPETR_INPUT_HW[1]) -> TriangleGeometry: + """``camera_data_store.cpp:287-316`` in float32 (module docstring).""" + src_h, src_w, dst_h, dst_w = int(src_h), int(src_w), int(dst_h), int(dst_w) + if min(src_h, src_w, dst_h, dst_w) <= 0: + raise ValueError(f"sizes must be positive: src {src_h}x{src_w}, dst {dst_h}x{dst_w}") + scale_h = F32(F32(dst_h) / F32(src_h)) + scale_w = F32(F32(dst_w) / F32(src_w)) + resize = scale_w if scale_h < scale_w else scale_h # std::max(scaleH, scaleW) + new_w = int(F32(F32(src_w) * resize)) # static_cast(int * float): truncation + new_h = int(F32(F32(src_h) * resize)) + crop_h = max(0, int(F32(F32(1.0) * F32(new_h))) - dst_h) # (1.0f - bottom_crop_portion) * newH, portion 0 + crop_w = max(0, int((new_w - dst_w) / 2)) if new_w > dst_w else 0 # C int division, then std::max(0, .) + return TriangleGeometry((src_h, src_w), (new_h, new_w), (dst_h, dst_w), (max(0, crop_h), max(0, crop_w)), + float(resize)) + + +# --------------------------------------------------------------------------------------------- arithmetic + + +def fma_f32(a: Any, b: Any, c: Any) -> np.ndarray: + """``fmaf(a, b, c)`` for float32 arrays: ``a * b + c`` rounded ONCE to float32 (round to nearest even), exactly. + + The float64 product of two float32 values is exact; the float64 sum may round, and a float64 result that lands + on a float32 tie the exact value does not sit on would round twice. The TwoSum error term detects that case and + the tie is broken towards the exact value.""" + a64 = np.asarray(a, dtype=F32).astype(F64) + b64 = np.asarray(b, dtype=F32).astype(F64) + c64 = np.asarray(c, dtype=F32).astype(F64) + p = a64 * b64 + s = p + c64 + r = np.asarray(s.astype(F32)) + bv = s - p + err = (p - (s - bv)) + (c64 - bv) # p + c == s + err exactly (Knuth's TwoSum) + bad = np.nonzero(np.broadcast_to(err, s.shape) != 0) + if bad[0].size: + sb, eb = s[bad], np.broadcast_to(err, s.shape)[bad] + rb = r[bad] + d = sb - rb.astype(F64) + nb = np.nextafter(rb, np.where(d > 0, np.inf, -np.inf).astype(F32)) + tie = (d != 0) & (sb == (rb.astype(F64) + nb.astype(F64)) * 0.5) + fix = tie & (np.sign(eb) == np.sign(d)) + rb = np.where(fix, nb, rb) + r = r.copy() + r[bad] = rb + return r + + +def _axis_taps(n_out: int, start: int, n_in: int, n_resized: int, fma: bool) -> Tuple[np.ndarray, np.ndarray]: + """Source index [n_out, T] and float32 weight [n_out, T] of every output row (or column), in the kernel's tap + order; taps past a pixel's window have weight 0 (index clamped into the image).""" + scale = F32(F32(n_in) / F32(n_resized)) + support = scale if scale > F32(1.0) else F32(1.0) + r = (np.arange(n_out, dtype=np.int64) + int(start)).astype(F32) # (float)(out + roi_start), exact + r5 = (r + F32(0.5)).astype(F32) + if fma: + centre = (r5.astype(F64) * F64(scale) - 0.5).astype(F32) # one rounding (exact in float64) + else: + centre = ((r5 * scale).astype(F32) - F32(0.5)).astype(F32) + lo = np.maximum(0, np.ceil((centre - support).astype(F32)).astype(np.int64)) + hi = np.minimum(n_in - 1, np.floor((centre + support).astype(F32)).astype(np.int64)) + n_taps = max(1, int((hi - lo).max()) + 1) + idx = lo[:, None] + np.arange(n_taps, dtype=np.int64)[None, :] + valid = idx <= hi[:, None] + idx = np.minimum(idx, n_in - 1) + d = (centre[:, None] - idx.astype(F32)).astype(F32) + w = (F32(1.0) - (np.abs(d) / support).astype(F32)).astype(F32) + w = np.maximum(F32(0.0), w).astype(F32) + w = np.where(valid, w, F32(0.0)).astype(F32) + return idx, w + + +@dataclass(frozen=True) +class TriangleResizeLUT: + """The per-size tables of ``resize_and_extract_roi_kernel``: build with :func:`triangle_resize_lut` (cached), + apply with :meth:`apply` (the per-pixel weighted mean, before the mean / std normalisation).""" + + geometry: TriangleGeometry + rows: np.ndarray # (roi_h, Ty) int64 source rows + row_w: np.ndarray # (roi_h, Ty) float32 wy (0 past the window) + cols: np.ndarray # (roi_w, Tx) int64 source columns + col_w: np.ndarray # (roi_w, Tx) float32 wx + fma: bool + + def apply(self, image: np.ndarray, *, out: Optional[np.ndarray] = None) -> np.ndarray: + """One uint8 image ``(src_h, src_w, C)`` (any channel count, channel order kept) -> float32 ``(C, roi_h, + roi_w)``: ``sum_c / sum_w`` (``sum_c`` where ``sum_w == 0``), exactly as the kernel before step 9.""" + g = self.geometry + img = np.asarray(image) + if img.ndim != 3 or img.dtype != np.uint8 or tuple(img.shape[:2]) != g.src_hw: + raise ValueError(f"expected a uint8 ({g.src_hw[0]}, {g.src_hw[1]}, C) image, got {img.dtype} {img.shape}") + roi_h, roi_w = g.roi_hw + cn = img.shape[2] + acc = np.zeros((cn, roi_h, roi_w), F32) + wsum = np.zeros((roi_h, roi_w), F32) + pix = np.empty((cn, roi_h, roi_w), F32) + planes = np.ascontiguousarray(img.transpose(2, 0, 1)) # (C, H, W) uint8 + # the source columns of every horizontal tap, once per image (float32 holds uint8 exactly) + cols = [planes[:, :, self.cols[:, tx]].astype(F32) for tx in range(self.cols.shape[1])] + for ty in range(self.rows.shape[1]): # y outer ... + rows = self.rows[:, ty] + wy = self.row_w[:, ty][:, None] + for tx in range(self.cols.shape[1]): # ... x inner, as the kernel + wx = self.col_w[:, tx][None, :] + w = (wx * wy).astype(F32) # w = wx * wy (rounded) + np.take(cols[tx], rows, axis=1, out=pix) # (C, roi_h, roi_w) pixels + if self.fma: + acc = fma_f32(pix, w, acc) # sum_c = fmaf(pix, w, sum_c) + wsum = fma_f32(np.broadcast_to(wx, w.shape), np.broadcast_to(wy, w.shape), wsum) + else: + np.multiply(pix, w, out=pix) # pix * w (rounded) + np.add(acc, pix, out=acc) # sum_c + . (rounded) + np.add(wsum, w, out=wsum) + pos = wsum > 0 + result = np.where(pos, acc / np.where(pos, wsum, F32(1.0)), acc).astype(F32) + if out is not None: + if out.shape != result.shape or out.dtype != F32: + raise ValueError(f"out must be float32 {result.shape}, got {out.dtype} {out.shape}") + out[...] = result + return out + return result + + +_TRIANGLE_LUTS = LUTCache(maxsize=16) + + +def triangle_resize_lut(src_hw: Tuple[int, int], dst_hw: Tuple[int, int] = STREAMPETR_INPUT_HW, *, + geometry: Optional[TriangleGeometry] = None, fma: bool = False) -> TriangleResizeLUT: + """The (cached) tables for one source size. ``geometry`` overrides the StreamPETR rule + (:func:`autoware_resize_geometry`) for other nodes of the same kernel family (resized size, ROI start).""" + g = geometry or autoware_resize_geometry(src_hw[0], src_hw[1], dst_hw[0], dst_hw[1]) + + def make() -> TriangleResizeLUT: + rows, row_w = _axis_taps(g.roi_hw[0], g.roi_start[0], g.src_hw[0], g.resized_hw[0], fma) + cols, col_w = _axis_taps(g.roi_hw[1], g.roi_start[1], g.src_hw[1], g.resized_hw[1], fma) + return TriangleResizeLUT(g, rows, row_w, cols, col_w, bool(fma)) + + key = ("triangle", g.src_hw, g.resized_hw, g.roi_hw, g.roi_start, bool(fma)) + return _TRIANGLE_LUTS.get(key, make) + + +# --------------------------------------------------------------------------------------------- the preset + + +def _preset(preset: Any) -> StreamPETRPreset: + if isinstance(preset, StreamPETRPreset): + return preset + try: + return STREAMPETR_PRESETS[str(preset)] + except KeyError: + raise ValueError(f"unknown normalisation preset {preset!r}; one of {sorted(STREAMPETR_PRESETS)}") from None + + +def streampetr_preprocess(image: np.ndarray, *, preset: Any = "autoware_main", channels: str = "rgb", + dst_hw: Tuple[int, int] = STREAMPETR_INPUT_HW, fma: bool = False, + out: Optional[np.ndarray] = None) -> np.ndarray: + """One camera image -> the float32 network input ``(3, 480, 640)`` of ``autoware_camera_streampetr``. + + ``image``: uint8 ``(H, W, 3)`` in the channel order ``channels`` (``"rgb"``: :func:`ttaw.io.load_image`, an + ``rgb8`` message; ``"bgr"``: OpenCV, a ``bgr8`` message). The preset fixes the plane order the kernel sees and + the statistics (:data:`STREAMPETR_PRESETS`); ``fma`` the contraction model (module docstring).""" + p = _preset(preset) + img = np.asarray(image) + if img.ndim != 3 or img.shape[2] != 3 or img.dtype != np.uint8: + raise ValueError(f"expected an (H, W, 3) uint8 image, got {img.dtype} {img.shape}") + if channels not in ("rgb", "bgr"): + raise ValueError("channels must be 'rgb' or 'bgr'") + if channels != p.planes: + img = img[:, :, ::-1] + lut = triangle_resize_lut(img.shape[:2], dst_hw, fma=fma) + v = lut.apply(img) # (3, H, W) float32 + mean = p.mean_f32()[:, None, None] + std = p.std_f32()[:, None, None] + res = ((v - mean).astype(F32) / std).astype(F32) # (sum_c - mean[c]) / std[c] + if out is not None: + if out.shape != res.shape or out.dtype != F32: + raise ValueError(f"out must be float32 {res.shape}, got {out.dtype} {out.shape}") + out[...] = res + return out + return res + + +def streampetr_preprocess_batch(images: Sequence[np.ndarray], *, preset: Any = "autoware_main", + channels: str = "rgb", dst_hw: Tuple[int, int] = STREAMPETR_INPUT_HW, + fma: bool = False, workers: int = 1, out: Optional[np.ndarray] = None) -> np.ndarray: + """The cameras of one frame -> float32 ``(N, 3, 480, 640)`` (each camera may have its own size). ``workers`` + threads over the cameras (numpy releases the GIL in the array passes).""" + imgs = list(images) + shape = (len(imgs), 3) + tuple(int(v) for v in dst_hw) + if out is None: + out = np.empty(shape, F32) + elif out.shape != shape or out.dtype != F32: + raise ValueError(f"out must be float32 {shape}, got {out.dtype} {out.shape}") + + def one(i: int) -> None: + streampetr_preprocess(imgs[i], preset=preset, channels=channels, dst_hw=dst_hw, fma=fma, out=out[i]) + + if workers > 1 and len(imgs) > 1: + with ThreadPoolExecutor(max_workers=min(int(workers), len(imgs))) as ex: + list(ex.map(one, range(len(imgs)))) + else: + for i in range(len(imgs)): + one(i) + return out diff --git a/code/tt_depthpro2/ttaw/io.py b/code/tt_depthpro2/ttaw/io.py new file mode 100644 index 0000000000000000000000000000000000000000..b017ba7d2ab8c1fc18de0fefc0b464b685825045 --- /dev/null +++ b/code/tt_depthpro2/ttaw/io.py @@ -0,0 +1,877 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C08 I/O: input decoding and output encoding shared by the Python API and the HTTP server of every bundle. + +One module, two callers: the bundle's ``api`` (Python objects: paths, bytes, numpy arrays) and its ``server.app`` +(JSON envelopes with base64 payloads). Both go through the same decoders, so ``model(...)`` and ``POST /predict`` +see bit-identical inputs (BUNDLE_CONVENTIONS.md section 7). + +Rules: + +- numpy only (PIL is imported lazily for images). No ttnn, no torch, no network: this module is imported by the + image's build-time ``verify:`` step and by host tests. +- Data parsing only: ``np.load(..., allow_pickle=False)``, no ``eval`` / ``pickle``. Every client mistake raises + :class:`InputError` (the server maps it to HTTP 400). + +Point-cloud envelope (``"points"`` in the request):: + + {"format": "bin" | "npy" | "npz" | "pcd" | "list", + "data": "", # all formats except "list" + "values": [[x, y, z, intensity], ...], # "list" only (small clouds) + "fields": ["x", "y", "z", "intensity"], # column names: required meaning for "bin" / "list" / plain arrays + "dtype": "float32", # "bin" only: float32 | float64 + "key": "points", # "npz" only (default: "points", else the first array) + "frame_id": "base_link"} + +Transforms (``T__from_``, 4x4, metres) accept several spellings, see :func:`parse_transform`. +""" +from __future__ import annotations + +import base64 +import binascii +import io +import json +import math +import re +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Iterable, Mapping, Optional, Sequence, Union + +import numpy as np + +__all__ = [ + "InputError", "PointCloud", "CameraImage", "POINT_FORMATS", "DEFAULT_POINT_FIELDS", "MAX_POINTS_DEFAULT", + "b64decode", "decode_points", "load_points", "decode_image", "load_image", "decode_cameras", "load_camera", + "load_cameras", "decode_rois", "parse_transform", + "parse_intrinsics", "resolve_calibration", "check_named_arrays", "decode_named_arrays", "load_named_arrays", + "encode_array", "encode_png", "to_jsonable", +] + +POINT_FORMATS = ("bin", "npy", "npz", "pcd", "list") +DEFAULT_POINT_FIELDS = ("x", "y", "z", "intensity") # Autoware's common LiDAR input layout +MAX_POINTS_DEFAULT = 2_000_000 # hard cap per cloud (memory guard, not a model limit) + + +class InputError(ValueError): + """A client-side input problem. The HTTP server answers 400 with ``str(err)``.""" + + +# ----------------------------------------------------------------------------------------------- base64 + +_B64_JUNK = re.compile(r"\s+") + + +def b64decode(s: Any, *, field: str = "data", max_bytes: Optional[int] = None) -> bytes: + """Decode standard or URL-safe base64; tolerates a ``data:...;base64,`` prefix, whitespace and missing padding.""" + if not isinstance(s, str) or not s: + raise InputError(f"{field} must be a non-empty base64 string") + if s.startswith("data:"): + comma = s.find(",") + if comma < 0: + raise InputError(f"{field}: malformed data: URI") + s = s[comma + 1:] + s = _B64_JUNK.sub("", s).replace("-", "+").replace("_", "/") + s += "=" * (-len(s) % 4) + if max_bytes is not None and len(s) * 3 // 4 > max_bytes + 3: + raise InputError(f"{field} is larger than {max_bytes} bytes") + try: + raw = base64.b64decode(s, validate=True) + except (binascii.Error, ValueError) as e: + raise InputError(f"{field} is not valid base64: {e}") from None + if not raw: + raise InputError(f"{field} is empty") + return raw + + +# ---------------------------------------------------------------------------------------- point clouds + +@dataclass +class PointCloud: + """An (N, C) float32 point array plus its column names and coordinate frame. Rows with a non-finite ``x``, + ``y`` or ``z`` (the first three columns when the cloud has no such names) are dropped at construction (PCL + ``is_dense=false`` clouds); the remaining rows keep their input order.""" + + points: np.ndarray + fields: tuple + frame_id: str = "base_link" + + def __post_init__(self) -> None: + self.fields = tuple(self.fields) + if self.points.ndim != 2 or self.points.shape[1] != len(self.fields): + raise InputError(f"points have shape {tuple(self.points.shape)} but {len(self.fields)} fields " + f"{list(self.fields)}") + if self.points.dtype != np.float32: + self.points = self.points.astype(np.float32) + named = [self.fields.index(n) for n in ("x", "y", "z") if n in self.fields] + xyz = self.points[:, named] if named else self.points[:, :3] + if not np.isfinite(xyz).all(): + keep = np.isfinite(xyz).all(axis=1) + self.points = np.ascontiguousarray(self.points[keep]) + + def __len__(self) -> int: + return int(self.points.shape[0]) + + def select(self, names: Sequence[str], *, fill: Optional[Mapping[str, float]] = None) -> np.ndarray: + """Columns ``names`` in that order (C-contiguous float32). A missing column is an error unless ``fill`` + gives it a constant (e.g. ``{"time_lag": 0.0}`` for a single sweep).""" + cols = [] + index = {n: i for i, n in enumerate(self.fields)} + for n in names: + if n in index: + cols.append(self.points[:, index[n]]) + elif fill is not None and n in fill: + cols.append(np.full(len(self), fill[n], np.float32)) + else: + raise InputError(f"point field {n!r} is required; the cloud has {list(self.fields)}") + return np.ascontiguousarray(np.stack(cols, axis=1), dtype=np.float32) + + +_PCD_TYPES = {("F", 4): " bytes: + """liblzf decompression (the codec of PCD ``DATA binary_compressed``). Pure Python: fine for test clouds, + slow (~1 s per 10 MB) for big ones -- send ``binary`` PCD or ``.npy`` when latency matters.""" + out = bytearray(out_len) + ip = op = 0 + n = len(data) + while ip < n: + ctrl = data[ip] + ip += 1 + if ctrl < 32: # literal run of ctrl + 1 bytes + ln = ctrl + 1 + if ip + ln > n or op + ln > out_len: + raise InputError("pcd: corrupt LZF stream (literal run)") + out[op:op + ln] = data[ip:ip + ln] + ip += ln + op += ln + else: # back reference + ln = ctrl >> 5 + ref = op - ((ctrl & 0x1F) << 8) - 1 + if ln == 7: + if ip >= n: + raise InputError("pcd: corrupt LZF stream (length)") + ln += data[ip] + ip += 1 + if ip >= n: + raise InputError("pcd: corrupt LZF stream (offset)") + ref -= data[ip] + ip += 1 + ln += 2 + if ref < 0 or op + ln > out_len: + raise InputError("pcd: corrupt LZF stream (back reference)") + if ref + ln <= op: + out[op:op + ln] = out[ref:ref + ln] + else: # overlapping copy: byte by byte, as liblzf does + for k in range(ln): + out[op + k] = out[ref + k] + op += ln + if op != out_len: + raise InputError(f"pcd: LZF produced {op} bytes, header says {out_len}") + return bytes(out) + + +def _parse_pcd(raw: bytes) -> tuple: + """PCD v0.7 (ascii / binary / binary_compressed) -> (float32 (N, C) array, field names).""" + header: dict = {} + pos = 0 + while True: + end = raw.find(b"\n", pos) + if end < 0: + raise InputError("pcd: header has no DATA line") + line = raw[pos:end].decode("ascii", "replace").strip() + pos = end + 1 + if not line or line.startswith("#"): + continue + key, _, rest = line.partition(" ") + header[key.upper()] = rest.split() + if key.upper() == "DATA": + break + try: + names = header["FIELDS"] + sizes = [int(v) for v in header["SIZE"]] + types = [v.upper() for v in header["TYPE"]] + counts = [int(v) for v in header.get("COUNT", ["1"] * len(names))] + npts = int(header.get("POINTS", [0])[0]) or int(header["WIDTH"][0]) * int(header.get("HEIGHT", ["1"])[0]) + mode = header["DATA"][0].lower() + except (KeyError, ValueError, IndexError) as e: + raise InputError(f"pcd: incomplete header ({e})") from None + if not (len(names) == len(sizes) == len(types) == len(counts)): + raise InputError("pcd: FIELDS/SIZE/TYPE/COUNT lengths differ") + cols, dt = [], [] + for n, s, t, c in zip(names, sizes, types, counts): + npt = _PCD_TYPES.get((t, s)) + if npt is None: + raise InputError(f"pcd: unsupported field type {t}{s} for {n!r}") + fname = n if n != "_" else f"_pad{len(dt)}" + dt.append((fname, npt, (c,)) if c > 1 else (fname, npt)) + if n != "_": + cols += [n] if c == 1 else [f"{n}_{k}" for k in range(c)] + dtype = np.dtype(dt) + body = raw[pos:] + if mode == "ascii": + try: + arr = np.loadtxt(io.StringIO(body.decode("ascii")), dtype=np.float64, ndmin=2) + except ValueError as e: + raise InputError(f"pcd: bad ascii body ({e})") from None + flat_names = [n if c == 1 else f"{n}_{k}" for n, c in zip(names, counts) for k in range(c)] + keep = [i for i, n in enumerate(flat_names) if not n.startswith("_")] + if arr.shape[1] != len(flat_names): + raise InputError(f"pcd: ascii rows have {arr.shape[1]} values, header declares {len(flat_names)}") + return arr[:, keep].astype(np.float32), tuple(cols) + if mode == "binary": + need = dtype.itemsize * npts + if len(body) < need: + raise InputError(f"pcd: binary body has {len(body)} bytes, needs {need}") + rec = np.frombuffer(body, dtype=dtype, count=npts) + elif mode == "binary_compressed": + if len(body) < 8: + raise InputError("pcd: binary_compressed body too short") + csize, usize = np.frombuffer(body[:8], " tuple: + cols, names = [], [] + for name in rec.dtype.names: + if name.startswith("_pad"): + continue + v = np.asarray(rec[name], dtype=np.float32) + if v.ndim == 1: + cols.append(v) + names.append(name) + else: + for k in range(v.shape[1]): + cols.append(v[:, k]) + names.append(f"{name}_{k}") + return np.stack(cols, axis=1) if cols else np.zeros((len(rec), 0), np.float32), tuple(names) + + +def _array_to_cloud(arr: np.ndarray, fields: Optional[Sequence[str]], frame_id: str, + default_fields: Sequence[str]) -> PointCloud: + if arr.dtype.names: # structured array (npy / npz written from a ROS PointCloud2 or PCL) + pts, names = _structured_to_2d(arr.reshape(-1)) + return PointCloud(pts, names, frame_id) + arr = np.asarray(arr) + if arr.ndim != 2: + raise InputError(f"points must be a 2-D (N, C) array, got shape {tuple(arr.shape)}") + if not np.issubdtype(arr.dtype, np.number): + raise InputError(f"points must be numeric, got dtype {arr.dtype}") + names = tuple(fields) if fields else tuple(default_fields[: arr.shape[1]]) + if len(names) != arr.shape[1]: + raise InputError(f"points have {arr.shape[1]} columns; give 'fields' (default {list(default_fields)})") + return PointCloud(np.ascontiguousarray(arr, dtype=np.float32), names, frame_id) + + +def _points_from_bytes(raw: bytes, fmt: str, *, fields: Optional[Sequence[str]] = None, dtype: str = "float32", + key: Optional[str] = None, frame_id: str = "base_link", + default_fields: Sequence[str] = DEFAULT_POINT_FIELDS) -> PointCloud: + if fmt == "bin": # raw little-endian rows, KITTI / Autoware dump style: N x len(fields) + names = tuple(fields) if fields else tuple(default_fields) + if dtype not in ("float32", "float64"): + raise InputError("bin dtype must be float32 or float64") + item = 4 if dtype == "float32" else 8 + row = item * len(names) + if len(raw) % row: + raise InputError(f"bin payload of {len(raw)} bytes is not a multiple of {len(names)} x {dtype} " + f"({row} bytes per point); check 'fields' (got {list(names)})") + arr = np.frombuffer(raw, dtype=" PointCloud: + """The JSON point-cloud envelope (module docstring) -> :class:`PointCloud`.""" + if not isinstance(spec, Mapping): + raise InputError("points must be an object {format, data, fields, ...}") + fmt = str(spec.get("format") or "bin").lower() + frame_id = str(spec.get("frame_id") or "base_link") + fields = spec.get("fields") + if fields is not None and (not isinstance(fields, (list, tuple)) or not all(isinstance(f, str) for f in fields)): + raise InputError("points.fields must be a list of column names") + if fmt == "list": + values = spec.get("values") + if not isinstance(values, list) or not values: + raise InputError("points.values must be a non-empty list of rows for format 'list'") + try: + arr = np.asarray(values, dtype=np.float32) + except (TypeError, ValueError) as e: + raise InputError(f"points.values: {e}") from None + cloud = _array_to_cloud(arr, fields, frame_id, default_fields) + else: + raw = b64decode(spec.get("data"), field="points.data", max_bytes=max_bytes) + cloud = _points_from_bytes(raw, fmt, fields=fields, dtype=str(spec.get("dtype") or "float32"), + key=spec.get("key"), frame_id=frame_id, default_fields=default_fields) + if len(cloud) > max_points: + raise InputError(f"{len(cloud)} points exceed the limit of {max_points}") + if len(cloud) == 0: + raise InputError("the point cloud is empty") + return cloud + + +PointsLike = Union[str, Path, bytes, np.ndarray, Mapping[str, Any], PointCloud] + + +def load_points(source: PointsLike, *, fields: Optional[Sequence[str]] = None, fmt: Optional[str] = None, + frame_id: str = "base_link", default_fields: Sequence[str] = DEFAULT_POINT_FIELDS) -> PointCloud: + """Python-API input: a path (.bin/.npy/.npz/.pcd), raw file bytes (give ``fmt``), an (N, C) array (or torch + tensor), a structured array, the JSON envelope, or a :class:`PointCloud`.""" + if isinstance(source, PointCloud): + return source + if isinstance(source, Mapping): + return decode_points(source, default_fields=default_fields) + if isinstance(source, (str, Path)): + p = Path(source) + ext = (fmt or p.suffix.lstrip(".")).lower() + if p.name.endswith(".pcd.bin"): # nuScenes naming: raw float32 x5 + ext = "bin" + return _points_from_bytes(p.read_bytes(), ext, fields=fields, frame_id=frame_id, default_fields=default_fields) + if isinstance(source, (bytes, bytearray, memoryview)): + if not fmt: + raise InputError("raw bytes need fmt= ('bin' | 'npy' | 'npz' | 'pcd')") + return _points_from_bytes(bytes(source), fmt, fields=fields, frame_id=frame_id, default_fields=default_fields) + if hasattr(source, "detach") and hasattr(source, "cpu"): # torch tensor, without importing torch + source = source.detach().cpu().numpy() + return _array_to_cloud(np.asarray(source), fields, frame_id, default_fields) + + +# ---------------------------------------------------------------------------------------------- images + +def _pil_to_rgb(im) -> np.ndarray: + if im.mode != "RGB": + im = im.convert("RGB") + return np.asarray(im, dtype=np.uint8) + + +def decode_image(raw: bytes, *, fmt: str = "auto", max_side: int = 8192) -> np.ndarray: + """PNG / JPEG (or .npy uint8 HxWx3) bytes -> RGB uint8 (H, W, 3).""" + if fmt == "npy": + try: + arr = np.load(io.BytesIO(raw), allow_pickle=False) + except ValueError as e: + raise InputError(f"image npy: {e}") from None + return load_image(arr) + from PIL import Image, UnidentifiedImageError # lazy: the API may never see an image + + try: + with Image.open(io.BytesIO(raw)) as im: + if max(im.size) > max_side: + raise InputError(f"image size {im.size} exceeds max side {max_side}") + return _pil_to_rgb(im) + except (UnidentifiedImageError, OSError) as e: + raise InputError(f"image could not be decoded as PNG/JPEG: {e}") from None + + +def load_image(image: Any) -> np.ndarray: + """Python-API image input: path, bytes, PIL image, uint8 HxWx3 / 3xHxW array or tensor, float array in [0, 1] + -> RGB uint8 (H, W, 3).""" + if isinstance(image, (str, Path)): + return decode_image(Path(image).read_bytes()) + if isinstance(image, (bytes, bytearray, memoryview)): + return decode_image(bytes(image)) + if hasattr(image, "mode") and hasattr(image, "size") and hasattr(image, "convert"): # PIL + return _pil_to_rgb(image) + 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] in (1, 3) and a.shape[2] not in (1, 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 (1, 3, 4): + raise InputError(f"image array must be HxWx3 (or 3xHxW / HxW), got {a.shape}") + a = a[:, :, :3] if a.shape[2] != 1 else np.repeat(a, 3, axis=2) + if np.issubdtype(a.dtype, np.floating): + a = np.clip(np.round(a * 255.0), 0, 255) + return np.ascontiguousarray(a, dtype=np.uint8) + + +@dataclass +class CameraImage: + """One camera of a (multi-)camera request: pixels + calibration, in the order the model expects.""" + + name: str + image: np.ndarray # RGB uint8 (H, W, 3) + intrinsics: Optional[np.ndarray] = None # (3, 3) float64, pixels + T_ref_from_camera: Optional[np.ndarray] = None # (4, 4) float64: camera -> reference frame (base_link / lidar) + distortion: Optional[dict] = None + timestamp_s: Optional[float] = None + extra: dict = field(default_factory=dict) + + +def decode_cameras(images: Iterable[Mapping[str, Any]], calibration: Optional[Mapping[str, Any]] = None, *, + order: Optional[Sequence[str]] = None, require_calibration: bool = True, + max_bytes: Optional[int] = None) -> list: + """``images[]`` (+ optional ``calibration.cameras``) -> list of :class:`CameraImage` in ``order``. + + Each image entry: ``{"camera": "CAM_FRONT", "data": , "format": "auto|png|jpeg|npy", + "intrinsics": ..., "T_ref_from_camera": ..., "distortion": {...}, "timestamp_s": ...}``. Inline calibration + wins over ``calibration.cameras[]``. ``order`` (the model's fixed camera order) reorders and checks + that every camera is present exactly once.""" + calib = dict((calibration or {}).get("cameras") or {}) + out = [] + for i, entry in enumerate(images or []): + if not isinstance(entry, Mapping): + raise InputError(f"images[{i}] must be an object") + name = str(entry.get("camera") or (order[i] if order and i < len(order) else f"cam{i}")) + raw = b64decode(entry.get("data"), field=f"images[{i}].data", max_bytes=max_bytes) + cam_cal = {**dict(calib.get(name) or {}), + **{k: v for k, v in entry.items() if k not in ("camera", "data", "format")}} + k = cam_cal.get("intrinsics") + t = cam_cal.get("T_ref_from_camera", cam_cal.get("extrinsics")) + if require_calibration and (k is None or t is None): + raise InputError(f"camera {name!r} needs 'intrinsics' and 'T_ref_from_camera' (inline or in calibration)") + out.append(CameraImage( + name=name, image=decode_image(raw, fmt=str(entry.get("format") or "auto")), + intrinsics=None if k is None else parse_intrinsics(k, field=f"{name}.intrinsics"), + T_ref_from_camera=None if t is None else parse_transform(t, field=f"{name}.T_ref_from_camera"), + distortion=cam_cal.get("distortion"), timestamp_s=cam_cal.get("timestamp_s"))) + if order: + by_name = {c.name: c for c in out} + if len(by_name) != len(out): + raise InputError("duplicate camera names in images[]") + missing = [n for n in order if n not in by_name] + extra = [n for n in by_name if n not in order] + if missing or extra: + raise InputError(f"cameras must be exactly {list(order)}; missing {missing}, unexpected {extra}") + out = [by_name[n] for n in order] + return out + + +_CAMERA_KEYS = ("intrinsics", "T_ref_from_camera", "extrinsics", "distortion", "timestamp_s") + + +def _with_calibration(cam: CameraImage, cal: Mapping[str, Any], require: bool) -> CameraImage: + """``cam`` with missing intrinsics / extrinsics / distortion / timestamp taken from ``cal`` (its calibration + entry), parsed and checked; ``require`` refuses a camera without K and T_ref_from_camera.""" + k = cam.intrinsics if cam.intrinsics is not None else cal.get("intrinsics") + t = cam.T_ref_from_camera if cam.T_ref_from_camera is not None else cal.get("T_ref_from_camera", + cal.get("extrinsics")) + if require and (k is None or t is None): + raise InputError(f"camera {cam.name!r} needs 'intrinsics' and 'T_ref_from_camera' (inline or in calibration)") + return CameraImage( + name=cam.name, image=cam.image, + intrinsics=None if k is None else parse_intrinsics(k, field=f"{cam.name}.intrinsics"), + T_ref_from_camera=None if t is None else parse_transform(t, field=f"{cam.name}.T_ref_from_camera"), + distortion=cam.distortion if cam.distortion is not None else cal.get("distortion"), + timestamp_s=cam.timestamp_s if cam.timestamp_s is not None else cal.get("timestamp_s"), extra=dict(cam.extra)) + + +def load_camera(source: Any, *, name: Optional[str] = None, calibration: Optional[Mapping[str, Any]] = None, + require_calibration: bool = False, max_bytes: Optional[int] = None) -> CameraImage: + """One camera of the Python API -> :class:`CameraImage` (RGB uint8 HxWx3, K / T parsed). ``source``: a + :class:`CameraImage` (what the server decodes ``/predict`` into), a mapping ``{"camera", "image" | "path", + "intrinsics", "T_ref_from_camera", "distortion", "timestamp_s"}`` or the ``/predict`` spelling ``{"camera", + "data": , ...}``, or any image :func:`load_image` accepts (then ``name`` names it). Calibration missing + inline comes from ``calibration["cameras"][]`` (inline wins, as in :func:`decode_cameras`).""" + cams = dict((calibration or {}).get("cameras") or {}) + if isinstance(source, CameraImage): + cam = source + elif isinstance(source, Mapping): + cam_name = str(source.get("camera") or name or "") + if not cam_name: + raise InputError("every camera needs a 'camera' name") + if "data" in source: + raw = b64decode(source.get("data"), field=f"{cam_name}.data", max_bytes=max_bytes) + image = decode_image(raw, fmt=str(source.get("format") or "auto")) + else: + src = source.get("image", source.get("path")) + if src is None: + raise InputError(f"camera {cam_name!r}: no 'image', 'path' or 'data'") + image = load_image(src) + unknown = sorted(set(source) - {"camera", "data", "format", "image", "path", *_CAMERA_KEYS}) + if unknown: + raise InputError(f"camera {cam_name!r}: unknown keys {unknown}") + cam = CameraImage(name=cam_name, image=image, intrinsics=source.get("intrinsics"), + T_ref_from_camera=source.get("T_ref_from_camera", source.get("extrinsics")), + distortion=source.get("distortion"), timestamp_s=source.get("timestamp_s")) + else: + if not name: + raise InputError("an image without a camera name: pass {'camera': name, 'image': ...} or a " + "{name: image} mapping") + cam = CameraImage(name=str(name), image=load_image(source)) + return _with_calibration(cam, dict(cams.get(cam.name) or {}), require_calibration) + + +def load_cameras(images: Any, calibration: Optional[Mapping[str, Any]] = None, *, + order: Optional[Sequence[str]] = None, require_calibration: bool = True, + calib_dir: Optional[Path] = None, max_bytes: Optional[int] = None) -> list: + """The Python-API twin of :func:`decode_cameras`: ``images`` (a list of :func:`load_camera` sources, or a + ``{camera name: image}`` mapping) + ``calibration`` (``{"cameras": {name: {...}}}``, or ``{"preset": name}`` + resolved in ``calib_dir``) -> :class:`CameraImage` list, reordered to ``order`` (every camera exactly once) when + given, else in input order. ``model(images=..., calibration=...)`` and ``POST /predict`` then see the same + cameras: the server passes the CameraImages it decoded, which come back unchanged.""" + if images is None: + raise InputError("this model needs 'images'" + (f": the cameras {list(order)}" if order else "")) + calib = resolve_calibration(calibration, calib_dir) if calibration is not None else None + if isinstance(images, Mapping) and not ({"camera", "image", "path", "data"} & set(images)): + entries = [(str(k), v) for k, v in images.items()] + else: + seq = list(images) if isinstance(images, (list, tuple)) else [images] + entries = [(None, v) for v in seq] + out = [load_camera(v, name=k, calibration=calib, require_calibration=require_calibration, max_bytes=max_bytes) + for k, v in entries] + names = [c.name for c in out] + if len(set(names)) != len(names): + raise InputError(f"duplicate camera names in images: {names}") + if order: + missing = [n for n in order if n not in names] + extra = [n for n in names if n not in order] + if missing or extra: + raise InputError(f"cameras must be exactly {list(order)}; missing {missing}, unexpected {extra}") + by_name = {c.name: c for c in out} + out = [by_name[n] for n in order] + return out + + +def decode_rois(rois: Any, *, cameras: Optional[Sequence[str]] = None, labels: Optional[Sequence[str]] = None, + max_rois: int = 4096) -> list: + """2-D detections given as an input (PointPainting's ``rois``, BUNDLE_CONVENTIONS.md 7.2): + ``[{"camera", "label", "score", "box_xyxy"}]`` -> the same list checked and normalised: ``camera`` a name (one of + ``cameras`` when given), ``label`` a name of ``labels`` or an index into it (returned as both ``label`` and + ``label_id`` when ``labels`` is given), ``score`` in [0, 1] (default 1.0), ``box_xyxy`` 4 finite pixels with + x0 <= x1 and y0 <= y1. ``None`` -> ``[]``.""" + if rois is None: + return [] + if not isinstance(rois, (list, tuple)): + raise InputError("rois must be a list of {camera, label, score, box_xyxy}") + if len(rois) > max_rois: + raise InputError(f"{len(rois)} rois exceed the limit of {max_rois}") + out = [] + for i, r in enumerate(rois): + where = f"rois[{i}]" + if not isinstance(r, Mapping): + raise InputError(f"{where} must be an object") + unknown = sorted(set(r) - {"camera", "label", "label_id", "score", "box_xyxy"}) + if unknown: + raise InputError(f"{where}: unknown keys {unknown}") + cam = r.get("camera") + if not isinstance(cam, str) or not cam: + raise InputError(f"{where}.camera must be a camera name") + if cameras is not None and cam not in cameras: + raise InputError(f"{where}.camera {cam!r} is not one of {list(cameras)}") + label = r.get("label", r.get("label_id")) + if isinstance(label, bool) or not isinstance(label, (str, int)): + raise InputError(f"{where}.label must be a class name or index") + entry: dict = {"camera": cam} + if labels is not None: + names = list(labels) + if isinstance(label, int): + if not 0 <= label < len(names): + raise InputError(f"{where}.label {label} is not an index of {names}") + entry.update(label=names[label], label_id=label) + elif label in names: + entry.update(label=label, label_id=names.index(label)) + else: + raise InputError(f"{where}.label {label!r} is not one of {names}") + else: + entry["label"] = label + score = r.get("score", 1.0) + try: + score = float(score) + except (TypeError, ValueError): + raise InputError(f"{where}.score must be a number") from None + if isinstance(r.get("score"), bool) or not 0.0 <= score <= 1.0: + raise InputError(f"{where}.score must be in [0, 1]") + try: + box = [float(v) for v in r.get("box_xyxy")] + except (TypeError, ValueError): + raise InputError(f"{where}.box_xyxy must be 4 numbers") from None + if len(box) != 4 or not all(math.isfinite(v) for v in box) or box[0] > box[2] or box[1] > box[3]: + raise InputError(f"{where}.box_xyxy must be 4 finite pixels with x0 <= x1 and y0 <= y1") + entry.update(score=score, box_xyxy=box) + out.append(entry) + return out + + +# ----------------------------------------------------------------------------------------- calibration + +def _rot_from_quat_wxyz(w: float, x: float, y: float, z: float) -> np.ndarray: + n = math.sqrt(w * w + x * x + y * y + z * z) + if n < 1e-9: + raise InputError("zero-length quaternion") + w, x, y, z = w / n, x / n, y / n, z / n + return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]], dtype=np.float64) + + +def _rot_from_rpy(roll: float, pitch: float, yaw: float) -> np.ndarray: + """tf2 ``setRPY`` convention used by Autoware's sensor_kit_calibration.yaml: R = Rz(yaw) Ry(pitch) Rx(roll).""" + cr, sr, cp, sp, cy, sy = (math.cos(roll), math.sin(roll), math.cos(pitch), math.sin(pitch), math.cos(yaw), + math.sin(yaw)) + return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr], + [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr], + [-sp, cp * sr, cp * cr]], dtype=np.float64) + + +def parse_transform(obj: Any, *, field: str = "transform") -> np.ndarray: + """A rigid transform -> (4, 4) float64. Accepted spellings: + + - a 4x4 (or 3x4) nested list / array, row-major, translation in the last column; + - ``{"matrix": 4x4}``; + - ``{"translation": [x, y, z], "rotation_wxyz": [w, x, y, z]}`` (nuScenes / BEVDet sample yaml), or + ``rotation_xyzw``, or ``rotation`` (3x3); + - ``{"x", "y", "z", "roll", "pitch", "yaw"}`` in metres / radians (Autoware ``sensor_kit_calibration.yaml``). + """ + try: + if isinstance(obj, Mapping): + if "matrix" in obj: + return parse_transform(obj["matrix"], field=field) + if "translation" in obj: + t = np.asarray(obj["translation"], dtype=np.float64).reshape(3) + if "rotation_wxyz" in obj: + r = _rot_from_quat_wxyz(*np.asarray(obj["rotation_wxyz"], dtype=np.float64).reshape(4)) + elif "rotation_xyzw" in obj: + x, y, z, w = np.asarray(obj["rotation_xyzw"], dtype=np.float64).reshape(4) + r = _rot_from_quat_wxyz(w, x, y, z) + elif "rotation" in obj: + r = np.asarray(obj["rotation"], dtype=np.float64).reshape(3, 3) + else: + raise InputError(f"{field}: translation needs rotation_wxyz | rotation_xyzw | rotation (3x3)") + elif {"x", "y", "z", "roll", "pitch", "yaw"} <= set(obj): + t = np.array([obj["x"], obj["y"], obj["z"]], dtype=np.float64) + r = _rot_from_rpy(float(obj["roll"]), float(obj["pitch"]), float(obj["yaw"])) + else: + raise InputError(f"{field}: unrecognised transform keys {sorted(obj)}") + m = np.eye(4) + m[:3, :3], m[:3, 3] = r, t + else: + m = np.asarray(obj, dtype=np.float64) + if m.shape == (3, 4): + m = np.vstack([m, [0.0, 0.0, 0.0, 1.0]]) + if m.shape != (4, 4): + raise InputError(f"{field}: expected a 4x4 matrix, got shape {m.shape}") + except (TypeError, ValueError) as e: + if isinstance(e, InputError): + raise + raise InputError(f"{field}: {e}") from None + if not np.isfinite(m).all() or not np.allclose(m[3], [0, 0, 0, 1], atol=1e-6): + raise InputError(f"{field}: last row must be [0, 0, 0, 1]") + r = m[:3, :3] + if not np.allclose(r.T @ r, np.eye(3), atol=1e-3) or np.linalg.det(r) < 0: + raise InputError(f"{field}: rotation part is not a proper rotation") + return m + + +def parse_intrinsics(obj: Any, *, field: str = "intrinsics") -> np.ndarray: + """3x3 K, a 3x4 projection P (its left 3x3), or ``{"fx", "fy", "cx", "cy"[, "skew"]}`` -> (3, 3) float64.""" + try: + if isinstance(obj, Mapping): + k = np.array([[obj["fx"], obj.get("skew", 0.0), obj["cx"]], [0.0, obj["fy"], obj["cy"]], [0.0, 0.0, 1.0]], + dtype=np.float64) + else: + k = np.asarray(obj, dtype=np.float64) + if k.shape == (3, 4): + k = k[:, :3] + if k.shape != (3, 3): + raise InputError(f"{field}: expected 3x3, got shape {k.shape}") + except (KeyError, TypeError, ValueError) as e: + if isinstance(e, InputError): + raise + raise InputError(f"{field}: {e}") from None + if not np.isfinite(k).all() or k[0, 0] <= 0 or k[1, 1] <= 0: + raise InputError(f"{field}: fx and fy must be positive") + return k + + +_PRESET_NAME = re.compile(r"[A-Za-z0-9_.-]+") + + +def resolve_calibration(calibration: Optional[Mapping[str, Any]], calib_dir: Optional[Path]) -> Optional[dict]: + """``{"preset": "", ...}`` -> the preset file ``/.json`` merged with the other keys + (request keys win); any other mapping is returned as a dict; ``None`` stays ``None``.""" + if calibration is None: + return None + if "preset" not in calibration: + return dict(calibration) + name = str(calibration["preset"]) + if calib_dir is None or not _PRESET_NAME.fullmatch(name) or not (Path(calib_dir) / f"{name}.json").is_file(): + raise InputError(f"unknown calibration preset {name!r}; see /info input.calibration_presets") + base = json.loads((Path(calib_dir) / f"{name}.json").read_text()) + return {**base, **{k: v for k, v in calibration.items() if k != "preset"}} + + +# ------------------------------------------------------------------------------ named tensors (planner) + +def check_named_arrays(arrays: Mapping[str, Any], schema: Mapping[str, tuple]) -> dict: + """``{name: array}`` checked against ``schema`` (name -> (shape with ``None`` for free dims, dtype)): every listed + name is required, unlisted names are rejected, shapes must match and values must convert to the dtype without + loss of kind (numbers only; a float into an integer slot must be integral, values must be finite). Returns + C-contiguous arrays of the schema dtypes; every problem raises :class:`InputError`.""" + if not isinstance(arrays, Mapping): + raise InputError("inputs must be an object {name: array}") + unknown = sorted(set(arrays) - set(schema)) + missing = sorted(set(schema) - set(arrays)) + if unknown or missing: + raise InputError(f"inputs: missing {missing}, unexpected {unknown}") + out = {} + for name, (shape, dtype) in schema.items(): + try: + a = np.asarray(arrays[name]) + except (TypeError, ValueError) as e: + raise InputError(f"inputs[{name!r}]: {e}") from None + if len(a.shape) != len(shape) or any(s is not None and s != d for s, d in zip(shape, a.shape)): + raise InputError(f"inputs[{name!r}] has shape {tuple(a.shape)}, expected {tuple(shape)}") + if not (np.issubdtype(a.dtype, np.number) or a.dtype == np.bool_): + raise InputError(f"inputs[{name!r}] must be numeric, got dtype {a.dtype}") + target = np.dtype(dtype) + if a.size and np.issubdtype(a.dtype, np.inexact) and not np.isfinite(a).all(): + raise InputError(f"inputs[{name!r}] holds non-finite values") + if a.size and np.issubdtype(target, np.integer) and a.dtype != np.bool_: + if np.issubdtype(a.dtype, np.inexact) and not np.array_equal(a, np.round(a)): + raise InputError(f"inputs[{name!r}] must hold integers ({target})") + info = np.iinfo(target) + if a.min() < info.min or a.max() > info.max: + raise InputError(f"inputs[{name!r}] has values outside the {target} range") + out[name] = np.ascontiguousarray(a.astype(target, copy=False)) + return out + + +def decode_named_arrays(spec: Mapping[str, Any], schema: Optional[Mapping[str, tuple]] = None, *, + max_bytes: Optional[int] = None) -> dict: + """``{"format": "npz", "data": }`` or ``{"format": "json", "arrays": {name: nested list}}`` -> + ``{name: ndarray}``. With ``schema`` the arrays are checked and cast by :func:`check_named_arrays`.""" + if not isinstance(spec, Mapping): + raise InputError("inputs must be an object {format, data | arrays}") + fmt = str(spec.get("format") or "npz").lower() + if fmt == "npz": + raw = b64decode(spec.get("data"), field="inputs.data", max_bytes=max_bytes) + try: + z = np.load(io.BytesIO(raw), allow_pickle=False) + arrays = {k: z[k] for k in z.files} + except (ValueError, OSError) as e: + raise InputError(f"inputs npz: {e}") from None + elif fmt == "json": + src = spec.get("arrays") + if not isinstance(src, Mapping): + raise InputError("inputs.arrays must be an object {name: nested list}") + arrays = {} + for k, v in src.items(): + try: + arrays[k] = np.asarray(v) + except (TypeError, ValueError) as e: + raise InputError(f"inputs.arrays[{k!r}]: {e}") from None + else: + raise InputError(f"inputs.format {fmt!r} must be 'npz' or 'json'") + return arrays if schema is None else check_named_arrays(arrays, schema) + + +def load_named_arrays(source: Any, schema: Optional[Mapping[str, tuple]] = None) -> dict: + """Python-API named inputs (planner): a ``{name: array}`` mapping, the JSON envelope of + :func:`decode_named_arrays`, an ``.npz`` path or its bytes -> ``{name: ndarray}`` (checked against ``schema`` + when given, so ``model(inputs=...)`` and ``POST /predict`` accept and refuse the same inputs).""" + if isinstance(source, Mapping) and "format" in source and ("data" in source or "arrays" in source): + return decode_named_arrays(source, schema) + if isinstance(source, (str, Path, bytes, bytearray, memoryview)): + try: + payload = Path(source).read_bytes() if isinstance(source, (str, Path)) else bytes(source) + with np.load(io.BytesIO(payload), allow_pickle=False) as z: + arrays = {k: z[k] for k in z.files} + except (ValueError, OSError) as e: + raise InputError(f"inputs npz: {e}") from None + elif isinstance(source, Mapping): + arrays = {str(k): (v.detach().cpu().numpy() if hasattr(v, "detach") else v) for k, v in source.items()} + else: + raise InputError(f"inputs must be a mapping, an .npz path or bytes, not {type(source).__name__}") + return arrays if schema is None else check_named_arrays(arrays, schema) + + +# ------------------------------------------------------------------------------------------- outputs + +def encode_array(arr: np.ndarray, *, fmt: str = "npz", key: str = "array") -> dict: + """A dense output for the JSON envelope: ``{"format", "key", "dtype", "shape", "data"}``. + + ``npz`` (default): base64 of ``np.savez`` -> ``np.load(io.BytesIO(base64.b64decode(d["data"])))[d["key"]]``; + ``npz_compressed``: the same with ``savez_compressed`` (smaller, slower); ``raw``: base64 of the little-endian + bytes (``np.frombuffer(..., dtype).reshape(shape)``); ``list``: nested JSON lists (small arrays only).""" + arr = np.asarray(arr) + head = {"format": fmt, "key": key, "dtype": str(arr.dtype), "shape": list(arr.shape)} + if fmt in ("npz", "npz_compressed"): + buf = io.BytesIO() + (np.savez_compressed if fmt == "npz_compressed" else np.savez)(buf, **{key: arr}) + return {**head, "data": base64.b64encode(buf.getvalue()).decode("ascii")} + if fmt == "raw": + a = arr.astype(arr.dtype.newbyteorder("<"), copy=False) + return {**head, "data": base64.b64encode(np.ascontiguousarray(a).tobytes()).decode("ascii")} + if fmt == "list": + return {**head, "data": arr.tolist()} + raise ValueError(f"unknown array encoding {fmt!r}") + + +def encode_png(image: np.ndarray, *, key: str = "image") -> dict: + """A uint8 mask / label map (H, W) or RGB image (H, W, 3) as base64 PNG (lossless): + ``{"format": "png", "key", "dtype", "shape", "data"}``.""" + from PIL import Image + + a = np.asarray(image) + if a.dtype != np.uint8: + if a.size and (a.min() < 0 or a.max() > 255): + raise ValueError("encode_png needs values in 0..255 (use encode_array for wider label ranges)") + a = a.astype(np.uint8) + if a.ndim not in (2, 3): + raise ValueError(f"encode_png expects (H, W) or (H, W, 3), got {a.shape}") + buf = io.BytesIO() + Image.fromarray(a).save(buf, format="PNG") + return {"format": "png", "key": key, "dtype": "uint8", "shape": list(a.shape), + "data": base64.b64encode(buf.getvalue()).decode("ascii")} + + +def to_jsonable(obj: Any) -> Any: + """numpy scalars / arrays -> plain Python, recursively. float32 / float16 scalars are rounded to 6 significant + digits (their precision); float64 scalars and array elements are kept exactly (timestamps, poses).""" + if isinstance(obj, Mapping): + return {str(k): to_jsonable(v) for k, v in obj.items()} + if isinstance(obj, (list, tuple)): + return [to_jsonable(v) for v in obj] + if isinstance(obj, np.ndarray): + return to_jsonable(obj.tolist()) + if isinstance(obj, (np.float32, np.float16)): + return float(f"{float(obj):.6g}") + if isinstance(obj, np.floating): + return float(obj) + if isinstance(obj, np.integer): + return int(obj) + if isinstance(obj, np.bool_): + return bool(obj) + if isinstance(obj, Path): + return str(obj) + return obj diff --git a/code/tt_depthpro2/ttaw/knobs.py b/code/tt_depthpro2/ttaw/knobs.py new file mode 100644 index 0000000000000000000000000000000000000000..beb8c02586bbca51f9ca92bc16f6150348740e14 --- /dev/null +++ b/code/tt_depthpro2/ttaw/knobs.py @@ -0,0 +1,177 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Optimization knobs: declared once, read from the environment once at model build, each an A/B switch. + +The rule every port follows (PLAN.md section 1.1; RP section 1.2): a knob's default is the measured best, the +server pins the full set in ``tt-model.yaml serve.env`` (:meth:`Knobs.serve_env` renders it), and a host test can +check the pins against the Python defaults. Setting an ``experiment`` knob logs a warning, so an A/B run is never +mistaken for the published configuration. + +Example:: + + KNOBS = Knobs("CENTERPOINT", [ + Knob("FUSED_HEAD", True, "merged 64->384->15 head convs (False = one conv per head)"), + Knob("BFP8_WEIGHTS", False, "bfp8 backbone weights", experiment=True), + Knob("NUM_CQS", 1, "command queues", choices=(1, 2)), + ]) + knobs = KNOBS.read() # at build; KnobValues is immutable + if knobs.FUSED_HEAD: ... +""" +from __future__ import annotations + +import logging +import os +from dataclasses import dataclass +from typing import Any, Dict, Iterable, Iterator, Mapping, Optional, Tuple + +__all__ = ["Knob", "Knobs", "KnobValues", "parse_bool"] + +log = logging.getLogger(__name__) + +_TRUE = {"1", "true", "yes", "on", "y"} +_FALSE = {"0", "false", "no", "off", "n", ""} + + +def parse_bool(text: str) -> bool: + value = str(text).strip().lower() + if value in _TRUE: + return True + if value in _FALSE: + return False + raise ValueError(f"{text!r} is not a boolean (1/0, true/false, on/off, yes/no)") + + +@dataclass(frozen=True) +class Knob: + """One switch. ``name`` is the suffix of the env variable ``_``; the type is the default's.""" + + name: str + default: Any + doc: str = "" + choices: Optional[Tuple[Any, ...]] = None + experiment: bool = False + + def __post_init__(self) -> None: + if not self.name or not self.name.replace("_", "").isalnum() or self.name.upper() != self.name: + raise ValueError(f"knob name {self.name!r} must be UPPER_SNAKE_CASE") + if self.choices is not None and self.default not in self.choices: + raise ValueError(f"knob {self.name}: default {self.default!r} not in {self.choices}") + + def parse(self, text: str) -> Any: + kind = type(self.default) + try: + if kind is bool: + value: Any = parse_bool(text) + elif kind is int: + value = int(text.strip()) + elif kind is float: + value = float(text.strip()) + else: + value = text.strip() + except ValueError as exc: + raise ValueError(f"{self.name}={text!r}: {exc}") from None + if self.choices is not None and value not in self.choices: + raise ValueError(f"{self.name}={value!r}: expected one of {self.choices}") + return value + + def render(self, value: Any) -> str: + if isinstance(value, bool): + return "1" if value else "0" + return str(value) + + +class KnobValues(Mapping): + """Immutable knob values with their source (``"default"`` / ``"env"`` / ``"override"``); attribute or item + access.""" + + def __init__(self, prefix: str, values: Dict[str, Any], sources: Dict[str, str]): + object.__setattr__(self, "_prefix", prefix) + object.__setattr__(self, "_values", dict(values)) + object.__setattr__(self, "_sources", dict(sources)) + + def __getattr__(self, name: str) -> Any: + if name.startswith("_"): + raise AttributeError(name) + try: + return self._values[name] + except KeyError: + raise AttributeError(f"no knob {name!r} (prefix {self._prefix})") from None + + def __setattr__(self, name: str, value: Any) -> None: + raise AttributeError("KnobValues is read-only (knobs are read once at build)") + + def __getitem__(self, name: str) -> Any: + return self._values[name] + + def __iter__(self) -> Iterator[str]: + return iter(self._values) + + def __len__(self) -> int: + return len(self._values) + + def source(self, name: str) -> str: + return self._sources[name] + + def overridden(self) -> Dict[str, Any]: + """Knobs not at their default source (set from the environment or by an explicit override).""" + return {k: v for k, v in self._values.items() if self._sources[k] != "default"} + + def as_dict(self) -> Dict[str, Any]: + return dict(self._values) + + def __repr__(self) -> str: + return f"KnobValues({self._prefix}: {self._values})" + + +class Knobs: + """The declared knob set of one model (env prefix = the bundle's ````).""" + + def __init__(self, prefix: str, knobs: Iterable[Knob]): + self.prefix = prefix.strip().upper() + self.knobs: Dict[str, Knob] = {} + for knob in knobs: + if knob.name in self.knobs: + raise ValueError(f"duplicate knob {knob.name}") + self.knobs[knob.name] = knob + + def env_name(self, name: str) -> str: + return f"{self.prefix}_{name}" + + def defaults(self) -> KnobValues: + return KnobValues(self.prefix, {n: k.default for n, k in self.knobs.items()}, + {n: "default" for n in self.knobs}) + + def read(self, env: Optional[Mapping[str, str]] = None, **overrides: Any) -> KnobValues: + """Defaults, then ``_`` environment values, then explicit ``overrides`` (e.g. from + ``from_pretrained`` keyword arguments). Raises on unparsable values; warns on experiment knobs.""" + env = os.environ if env is None else env + values, sources = {}, {} + for name, knob in self.knobs.items(): + raw = env.get(self.env_name(name)) + if raw is not None and raw.strip() != "": + values[name], sources[name] = knob.parse(raw), "env" + else: + values[name], sources[name] = knob.default, "default" + for name, value in overrides.items(): + if name not in self.knobs: + raise KeyError(f"unknown knob {name!r}; have {sorted(self.knobs)}") + knob = self.knobs[name] + values[name], sources[name] = knob.parse(knob.render(value)), "override" + experiments = [n for n, k in self.knobs.items() if k.experiment and values[n] != k.default] + if experiments: + log.warning("%s: experiment knobs set (%s); results are not the published configuration", self.prefix, + ", ".join(f"{self.env_name(n)}={self.knobs[n].render(values[n])}" for n in experiments)) + return KnobValues(self.prefix, values, sources) + + def serve_env(self, values: Optional[Mapping[str, Any]] = None) -> Dict[str, str]: + """``{"_": ""}`` for pinning in ``tt-model.yaml serve.env`` (defaults if no values).""" + vals = values if values is not None else self.defaults() + return {self.env_name(n): k.render(vals[n]) for n, k in self.knobs.items()} + + def doc_table(self) -> str: + """A Markdown table of the knobs (for SERVING.md / OPT_REPORT.md).""" + rows = ["| variable | default | meaning |", "|---|---|---|"] + for name, knob in self.knobs.items(): + extra = f" (one of {', '.join(map(str, knob.choices))})" if knob.choices else "" + tag = " **experiment**" if knob.experiment else "" + rows.append(f"| `{self.env_name(name)}` | `{knob.render(knob.default)}` | {knob.doc}{extra}{tag} |") + return "\n".join(rows) diff --git a/code/tt_depthpro2/ttaw/metrics.py b/code/tt_depthpro2/ttaw/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..c48539b2deb99b5631aa1e97baba586146bd8240 --- /dev/null +++ b/code/tt_depthpro2/ttaw/metrics.py @@ -0,0 +1,281 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C06 metrics: device-vs-reference agreement measures (host side, numpy only, float64 arithmetic). + +Inputs may be numpy arrays, torch tensors (bf16 included) or nested lists. Gates are applied by +:mod:`.golden` (``GateRegistry``); these functions only measure. + +========================== ===================================================================================== +function use +========================== ===================================================================================== +``pcc`` dense Pearson correlation (the default gate metric) +``masked_pcc`` PCC over the elements where a mask is true (valid pillars, in-range points) +``valid_row_pcc`` PCC over the first ``n_valid`` rows of a fixed-capacity buffer +``error_stats`` max / mean abs error, relative L2, PCC in one dict +``argmax_agreement`` fraction of positions whose argmax over ``axis`` agrees (segmentation logits) +``label_agreement`` fraction of equal labels (decided class maps) +``mask_iou`` ``mean_iou`` binary-mask IoU; per-class and mean IoU of label maps +``box_iou_xyxy`` pairwise IoU of 2-D boxes +``topk_overlap`` |A ∩ B| / k of two index sets (data-dependent selections) +``topk_set_overlap`` the same, computed from two score arrays +``match_detections`` greedy same-label matching by BEV-centre distance: recall, precision, errors +``ade_fde`` average / final displacement error of trajectories +========================== ===================================================================================== +""" +from __future__ import annotations + +import math +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np + +__all__ = [ + "as_array", + "pcc", + "masked_pcc", + "valid_row_pcc", + "error_stats", + "argmax_agreement", + "label_agreement", + "mask_iou", + "mean_iou", + "box_iou_xyxy", + "topk_overlap", + "topk_set_overlap", + "DetectionMatch", + "match_detections", + "ade_fde", +] + + +def as_array(x: Any, dtype: Optional[Any] = None) -> np.ndarray: + """numpy / torch (any dtype, bf16 widened to float32) / list -> numpy, without importing torch.""" + if hasattr(x, "detach") and hasattr(x, "cpu"): + t = x.detach().cpu() + if str(t.dtype) == "torch.bfloat16": + t = t.float() + x = t.numpy() + a = np.asarray(x) + return a if dtype is None else a.astype(dtype, copy=False) + + +def _pcc_flat(a: np.ndarray, b: np.ndarray) -> float: + if a.shape != b.shape: + raise ValueError(f"shape mismatch: {a.shape} vs {b.shape}") + if a.size == 0: + return float("nan") + if not (np.isfinite(a).all() and np.isfinite(b).all()): + return float("nan") + # A constant side is detected exactly (max == min), never from the centred sum of squares: the mean of a + # constant array is not exact in floating point (np.full(1000, 0.1).mean() != 0.1), so the centred values hold + # rounding noise that would correlate perfectly with the other side's noise (two different constants gave +-1). + const_a, const_b = a.max() == a.min(), b.max() == b.min() + if const_a or const_b: # equal constants agree perfectly, anything else does not + return 1.0 if (const_a and const_b and np.allclose(a, b)) else 0.0 + da = a - a.mean() + db = b - b.mean() + sa = float(np.dot(da, da)) + sb = float(np.dot(db, db)) + return float(np.dot(da, db) / math.sqrt(sa * sb)) + + +def pcc(test: Any, ref: Any) -> float: + """Pearson correlation of two equally shaped tensors (float64). NaN if any value is non-finite or both are + empty; when a side is constant: 1.0 for two equal constants (``np.allclose``), else 0.0 (two different + constants included).""" + return _pcc_flat(as_array(test, np.float64).reshape(-1), as_array(ref, np.float64).reshape(-1)) + + +def masked_pcc(test: Any, ref: Any, mask: Any) -> float: + """PCC over ``mask`` (broadcastable to the tensors' shape).""" + a, b = as_array(test, np.float64), as_array(ref, np.float64) + if a.shape != b.shape: + raise ValueError(f"shape mismatch: {a.shape} vs {b.shape}") + m = np.broadcast_to(as_array(mask).astype(bool), a.shape) + return _pcc_flat(a[m], b[m]) + + +def valid_row_pcc(test: Any, ref: Any, n_valid: Optional[int] = None, *, rows: Any = None, axis: int = 0) -> float: + """PCC over the valid rows of fixed-capacity buffers: the first ``n_valid`` along ``axis``, or the rows where + the boolean vector ``rows`` is true.""" + a, b = as_array(test, np.float64), as_array(ref, np.float64) + if (n_valid is None) == (rows is None): + raise ValueError("give exactly one of n_valid and rows") + if rows is None: + idx = np.arange(int(n_valid)) + else: + idx = np.flatnonzero(as_array(rows).astype(bool)) + return _pcc_flat(np.take(a, idx, axis=axis).reshape(-1), np.take(b, idx, axis=axis).reshape(-1)) + + +def error_stats(test: Any, ref: Any) -> Dict[str, float]: + """``{"pcc", "max_abs", "mean_abs", "rel_l2", "n"}`` (``rel_l2 = ||t - r|| / ||r||``).""" + a, b = as_array(test, np.float64), as_array(ref, np.float64) + if a.shape != b.shape: + raise ValueError(f"shape mismatch: {a.shape} vs {b.shape}") + d = np.abs(a - b) + ref_norm = float(np.linalg.norm(b)) + return {"pcc": _pcc_flat(a.reshape(-1), b.reshape(-1)), + "max_abs": float(d.max()) if d.size else 0.0, + "mean_abs": float(d.mean()) if d.size else 0.0, + "rel_l2": float(np.linalg.norm(a - b) / ref_norm) if ref_norm > 0 else float(np.linalg.norm(a - b)), + "n": int(a.size)} + + +def argmax_agreement(test_logits: Any, ref_logits: Any, *, axis: int = -1, mask: Any = None) -> float: + """Fraction of positions where ``argmax`` over ``axis`` agrees (ties resolve to the lowest index, as numpy + and Autoware's decision rules do). ``mask`` selects positions (shape without ``axis``).""" + a = np.argmax(as_array(test_logits), axis=axis) + b = np.argmax(as_array(ref_logits), axis=axis) + return label_agreement(a, b, mask=mask) + + +def label_agreement(test_labels: Any, ref_labels: Any, *, mask: Any = None) -> float: + """Fraction of equal labels (optionally over ``mask``). NaN when nothing is selected.""" + a, b = as_array(test_labels), as_array(ref_labels) + if a.shape != b.shape: + raise ValueError(f"shape mismatch: {a.shape} vs {b.shape}") + eq = a == b + if mask is not None: + eq = eq[np.broadcast_to(as_array(mask).astype(bool), eq.shape)] + return float(eq.mean()) if eq.size else float("nan") + + +def mask_iou(test_mask: Any, ref_mask: Any) -> float: + """IoU of two binary masks (1.0 when both are empty).""" + a, b = as_array(test_mask).astype(bool), as_array(ref_mask).astype(bool) + union = np.logical_or(a, b).sum() + return 1.0 if union == 0 else float(np.logical_and(a, b).sum() / union) + + +def mean_iou(test_labels: Any, ref_labels: Any, num_classes: int, *, + ignore_index: Optional[int] = None) -> Tuple[float, List[float]]: + """``(mIoU over classes present in either map, per-class IoU with NaN for absent classes)``.""" + a, b = as_array(test_labels).reshape(-1), as_array(ref_labels).reshape(-1) + if a.shape != b.shape: + raise ValueError(f"shape mismatch: {a.shape} vs {b.shape}") + if ignore_index is not None: + keep = b != ignore_index + a, b = a[keep], b[keep] + per = [] + for c in range(num_classes): + inter = np.logical_and(a == c, b == c).sum() + union = np.logical_or(a == c, b == c).sum() + per.append(float(inter / union) if union else float("nan")) + valid = [v for v in per if not math.isnan(v)] + return (float(np.mean(valid)) if valid else float("nan")), per + + +def box_iou_xyxy(boxes_a: Any, boxes_b: Any) -> np.ndarray: + """Pairwise IoU ``[N, M]`` of axis-aligned boxes ``[x1, y1, x2, y2]`` (float64).""" + a = as_array(boxes_a, np.float64).reshape(-1, 4) + b = as_array(boxes_b, np.float64).reshape(-1, 4) + ix1 = np.maximum(a[:, None, 0], b[None, :, 0]) + iy1 = np.maximum(a[:, None, 1], b[None, :, 1]) + ix2 = np.minimum(a[:, None, 2], b[None, :, 2]) + iy2 = np.minimum(a[:, None, 3], b[None, :, 3]) + inter = np.clip(ix2 - ix1, 0, None) * np.clip(iy2 - iy1, 0, None) + area_a = np.clip(a[:, 2] - a[:, 0], 0, None) * np.clip(a[:, 3] - a[:, 1], 0, None) + area_b = np.clip(b[:, 2] - b[:, 0], 0, None) * np.clip(b[:, 3] - b[:, 1], 0, None) + union = area_a[:, None] + area_b[None, :] - inter + with np.errstate(invalid="ignore", divide="ignore"): + return np.where(union > 0, inter / union, 0.0) + + +def topk_overlap(test_indices: Any, ref_indices: Any, k: Optional[int] = None) -> float: + """``|set(test[:k]) ∩ set(ref[:k])| / k`` (``k`` defaults to ``len(ref)``).""" + a, b = as_array(test_indices).reshape(-1), as_array(ref_indices).reshape(-1) + k = len(b) if k is None else int(k) + if k <= 0: + return float("nan") + return len(set(a[:k].tolist()) & set(b[:k].tolist())) / k + + +def topk_set_overlap(test_scores: Any, ref_scores: Any, k: int) -> float: + """Overlap of the top-``k`` index sets of two score arrays (flattened; stable descending order).""" + a, b = as_array(test_scores, np.float64).reshape(-1), as_array(ref_scores, np.float64).reshape(-1) + ta = np.argsort(-a, kind="stable")[:k] + tb = np.argsort(-b, kind="stable")[:k] + return topk_overlap(ta, tb, k) + + +@dataclass +class DetectionMatch: + """Result of :func:`match_detections` (``pairs`` are ``(test_index, ref_index)``).""" + + pairs: List[Tuple[int, int]] + n_test: int + n_ref: int + center_errors: List[float] = field(default_factory=list) + score_errors: List[float] = field(default_factory=list) + + @property + def matched(self) -> int: + return len(self.pairs) + + @property + def recall(self) -> float: + return self.matched / self.n_ref if self.n_ref else 1.0 + + @property + def precision(self) -> float: + return self.matched / self.n_test if self.n_test else 1.0 + + def to_dict(self) -> Dict[str, Any]: + def stat(v: List[float], fn) -> Optional[float]: + return float(fn(v)) if v else None + + return {"n_test": self.n_test, "n_ref": self.n_ref, "matched": self.matched, "recall": self.recall, + "precision": self.precision, "center_err_mean": stat(self.center_errors, np.mean), + "center_err_max": stat(self.center_errors, np.max), "score_err_max": stat(self.score_errors, np.max), + "score_err_mean": stat(self.score_errors, np.mean)} + + +def _centers(x: Any, n: int, dims: int) -> np.ndarray: + a = as_array(x, np.float64) + if a.size == 0: + return np.zeros((n, dims)) + if a.size % max(n, 1) or n == 0: + raise ValueError(f"{a.shape[0] if a.ndim else 0} centres for {n} labels: lengths differ") + return a.reshape(n, -1)[:, :dims] + + +def match_detections(test_centers: Any, test_labels: Any, test_scores: Any, ref_centers: Any, ref_labels: Any, + ref_scores: Any, *, max_dist: float = 0.5, dims: int = 2, + same_label: bool = True) -> DetectionMatch: + """Greedy matching: reference boxes in descending score order each take the nearest unused test box (same + label unless ``same_label=False``) within ``max_dist`` of its centre, measured over the first ``dims`` + coordinates (2 = BEV x/y). ``*_centers`` are ``[N, >=dims]`` (box arrays ``[N, 7]`` work as-is). A box with a + non-finite centre never matches (it costs recall / precision; it does not block the other boxes).""" + tl, rl = as_array(test_labels).reshape(-1), as_array(ref_labels).reshape(-1) + ts, rs = as_array(test_scores, np.float64).reshape(-1), as_array(ref_scores, np.float64).reshape(-1) + if len(ts) != len(tl) or len(rs) != len(rl): + raise ValueError(f"labels / scores lengths differ: test {len(tl)}/{len(ts)}, ref {len(rl)}/{len(rs)}") + tc, rc = _centers(test_centers, len(tl), dims), _centers(ref_centers, len(rl), dims) + used = np.zeros(len(tl), bool) + result = DetectionMatch([], len(tl), len(rl)) + for i in np.argsort(-rs, kind="stable"): + if not len(tl): + break + d = np.linalg.norm(tc - rc[i], axis=1) + bad = used | ~np.isfinite(d) # np.argmin would pick a NaN distance before any real one + if same_label: + bad |= tl != rl[i] + d[bad] = np.inf + j = int(np.argmin(d)) + if d[j] <= max_dist: + used[j] = True + result.pairs.append((j, int(i))) + result.center_errors.append(float(d[j])) + result.score_errors.append(abs(float(ts[j] - rs[i]))) + return result + + +def ade_fde(pred: Any, ref: Any, *, dims: int = 2) -> Tuple[float, float]: + """Average and final displacement errors of trajectories ``[..., T, >=dims]`` (Euclidean over the first + ``dims`` coordinates; averaged over all leading dims).""" + p, r = as_array(pred, np.float64), as_array(ref, np.float64) + if p.shape[:-1] != r.shape[:-1]: + raise ValueError(f"trajectory shapes differ: {p.shape} vs {r.shape}") + disp = np.linalg.norm(p[..., :dims] - r[..., :dims], axis=-1) + return float(disp.mean()), float(disp[..., -1].mean()) diff --git a/code/tt_depthpro2/ttaw/models/__init__.py b/code/tt_depthpro2/ttaw/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..629bcb240c1ee4a9c97cde7e172c7fc2f2e07971 --- /dev/null +++ b/code/tt_depthpro2/ttaw/models/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Shared device sub-networks of the Autoware ports (PLAN.md section 1.2), built from host (numpy) weights with +BatchNorm already folded, on the C17 builders (``ttaw.ops.conv``: ``FeatureMap``, ``Conv2d``, ``KSplitConv``, +``ConvTranspose2d``); every op traceable, weights prepared by the first (eager) call. + +================== ====== ========================================================================= +module id what it provides +================== ====== ========================================================================= +``second`` C24 SECOND backbone and SECONDFPN neck (CenterPoint, PointPainting, TransFusion, + BEVFusion); ``RowLinear`` (1x1 convs as ``ttnn.linear`` on NHWC rows) +``centerhead`` C25 CenterPoint dense head: K-split shared conv, merged sibling heads, one packed + fp32 output +``pillars`` C24 PillarFeatureNet of the pillar detectors (CenterPoint, PointPainting, TransFusion): + identity-folded split PFN on 32-slot pillar tiles, input packing, ``FrameStaging`` +``resnet`` C27 ResNet bottleneck / basic-block builders from a parameter provider, cameras as + batch (BEVDet image backbone + CustomResNet; BEVFormer, METEOR) +``transfusion_head`` C26 TransFusion query head (TransFusion, BEVFusion, PTv3): C21 selection, query init + with QPE / KPE tables, one decoder layer on C20, merged prediction heads +``sparse_encoder`` C28 gather-GEMM sparse-conv encoder (BEVFusion, PTv3): one tile-ordered TILE + PADDED + gather + one matmul per layer on C13 rulebooks, residual blocks, two-term tables +================== ====== ========================================================================= + +Importing a module never imports ttnn / torch (rule of the package): device work happens in the layer calls. +""" + +__all__ = ["second", "centerhead", "pillars", "resnet", "transfusion_head", "sparse_encoder"] diff --git a/code/tt_depthpro2/ttaw/models/centerhead.py b/code/tt_depthpro2/ttaw/models/centerhead.py new file mode 100644 index 0000000000000000000000000000000000000000..4e25b71096b502e02230aba8bfa2b9bc1522821e --- /dev/null +++ b/code/tt_depthpro2/ttaw/models/centerhead.py @@ -0,0 +1,164 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C25: the CenterPoint dense head on the device (PLAN.md section 1.2 row C25; CenterPoint, PointPainting). + +mmdet3d ``CenterHead`` (single task, as Autoware's exports): ``shared = relu(conv3x3(concat[d_0..d_n]))``, then per +output head ``out_h = conv1x1(relu(conv1x1(shared)))``. Two exact rewrites (each differs from the literal graph +only by summation order; probe P14 and research/centerpoint/SPEC.md 8.1): + +- **K-split shared conv** (default; C17 ``KSplitConv``): ``conv(concat[d_i], W) == sum_i conv(d_i, W_i)``, the bias + on the first partial conv and the ReLU fused into the last add. The concat (CenterPoint base: 177 MB) never + exists; P14: 3.6 ms against 14.8 ms for the full-K conv, and more accurate. ``accumulate_dtype="float32"`` keeps + the partials in fp32; +- **merged sibling heads**: the six 1x1 -> ReLU -> 1x1 heads become two matmuls on NHWC rows (:class:`..second. + RowLinear`): ``hidden = relu(x @ Wh + bh)`` with ``Wh = [Wh_1 | ... | Wh_6]`` (``64 -> 6*64``), then ``out = + hidden @ Wo + bo`` with the block-diagonal ``Wo`` (``6*64 -> sum C_h``, zero-padded to a multiple of 32 columns so + the output tensor is tile-exact). + +The output is ONE ``[1, 1, H*W, C_pad]`` tensor (fp32 by default: the logits feed host thresholds), i.e. one +readback; :meth:`CenterHead.unpack` splits the host rows into ``{name: (C, H, W)}``. Module names for the precision +policy: ``.shared``, ``.hidden``, ``.out``. +""" +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Sequence, Tuple + +import numpy as np + +from ..ops.conv import Conv2d, FeatureMap, KSplitConv +from ..precision import PrecisionPolicy +from .second import ConvSpec, RowLinear, _precision, _to_dram, free_maps + +__all__ = ["CenterHead", "HeadSpec", "merge_heads", "centerhead_numpy"] + +HeadSpec = Tuple[str, ConvSpec, ConvSpec] # (output name, hidden 1x1 + ReLU, final 1x1) + + +def merge_heads(heads: Sequence[HeadSpec], *, pad_to: int = 32 + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, List[Tuple[str, int, int]]]: + """``(Wh [Cin, sum hidden], bh, Wo [sum hidden, C_pad], bo [C_pad], slices)`` of the merged heads; ``slices`` + lists ``(name, start, stop)`` of each head's output columns; columns past ``sum C_h`` are zero.""" + if not heads: + raise ValueError("no heads") + cin = heads[0][1].in_channels + wh, bh, rows, cols = [], [], 0, 0 + for name, hidden, final in heads: + if hidden.kind != "conv" or final.kind != "conv" or hidden.kernel != 1 or final.kernel != 1: + raise ValueError(f"head {name!r}: merged heads need 1x1 convs") + if hidden.in_channels != cin or final.in_channels != hidden.out_channels: + raise ValueError(f"head {name!r}: channel mismatch") + if not hidden.relu or final.relu: + raise ValueError(f"head {name!r}: expected a ReLU after the hidden conv only") + wh.append(np.asarray(hidden.weight, np.float32)[:, :, 0, 0].T) + bh.append(np.zeros(hidden.out_channels, np.float32) if hidden.bias is None + else np.asarray(hidden.bias, np.float32)) + rows += hidden.out_channels + cols += final.out_channels + cpad = -(-cols // pad_to) * pad_to + wo = np.zeros((rows, cpad), np.float32) + bo = np.zeros(cpad, np.float32) + slices, r, c = [], 0, 0 + for name, hidden, final in heads: + co = final.out_channels + wo[r:r + hidden.out_channels, c:c + co] = np.asarray(final.weight, np.float32)[:, :, 0, 0].T + if final.bias is not None: + bo[c:c + co] = np.asarray(final.bias, np.float32) + slices.append((name, c, c + co)) + r += hidden.out_channels + c += co + return (np.ascontiguousarray(np.concatenate(wh, axis=1)), np.concatenate(bh).astype(np.float32), wo, bo, + slices) + + +class CenterHead: + """Shared conv (K-split over ``split``) + merged heads; see the module docstring. + + ``shared``: the 3x3 :class:`ConvSpec` over the concatenated inputs (ReLU after); ``split``: channels of each + input, in concat order; ``heads``: ``(name, hidden, final)`` in output order. ``k_split=False`` runs one conv + on a device concat instead (A/B only). ``output_dtype``: of the packed head output (``"float32"``). The shared + conv's output dtype is its precision's ``activations`` (bf16 by default); ``accumulate_dtype`` (default: the same) + is the dtype of the K-split partial sums.""" + + def __init__(self, shared: ConvSpec, split: Sequence[int], heads: Sequence[HeadSpec], *, + policy: Optional[PrecisionPolicy] = None, prefix: str = "head", output_dtype: str = "float32", + k_split: bool = True, accumulate_dtype: Optional[str] = None): + if shared.kind != "conv" or shared.stride != 1 or not shared.relu: + raise ValueError("the shared conv must be a stride-1 conv followed by a ReLU") + self.prefix = prefix + self.split = [int(s) for s in split] + if sum(self.split) != shared.in_channels: + raise ValueError(f"split {self.split} does not cover the {shared.in_channels} shared-conv inputs") + self.k_split = bool(k_split) and len(self.split) > 1 + pad = shared.kernel // 2 if shared.padding is None else int(shared.padding) + prec = _precision(policy, f"{prefix}.shared") + if self.k_split: + self.shared = KSplitConv(shared.weight, shared.bias, self.split, activation="relu", padding=pad, + precision=prec, accumulate_dtype=accumulate_dtype or prec.activations, + output_dtype=prec.activations, name=f"{prefix}.shared") + else: + self.shared = Conv2d(shared.weight, shared.bias, padding=pad, activation="relu", precision=prec, + output_dtype=prec.activations, name=f"{prefix}.shared") + wh, bh, wo, bo, self.slices = merge_heads(heads) + self.out_channels = self.slices[-1][2] + self.padded_channels = int(wo.shape[1]) + hidden_prec = _precision(policy, f"{prefix}.hidden") + self.hidden = RowLinear(wh, bh, activation="relu", precision=hidden_prec, + output_dtype=hidden_prec.activations, name=f"{prefix}.hidden") + self.out = RowLinear(wo, bo, activation=None, precision=_precision(policy, f"{prefix}.out"), + output_dtype=output_dtype, name=f"{prefix}.out") + + def shared_forward(self, inputs: Sequence[FeatureMap]) -> FeatureMap: + """``relu(conv3x3(concat(inputs)))`` (inputs are kept), DRAM interleaved.""" + import ttnn + + if [x.channels for x in inputs] != self.split: + raise ValueError(f"{self.prefix}: inputs have {[x.channels for x in inputs]} channels, " + f"expected {self.split}") + if self.k_split: + return _to_dram(self.shared(inputs)) + cat = inputs[0].with_tensor(ttnn.concat([x.tensor for x in inputs], dim=-1), sum(self.split)) + out = _to_dram(self.shared(cat)) + free_maps(cat) + return out + + def heads_forward(self, shared: FeatureMap) -> FeatureMap: + """Merged heads on the shared map -> ``[1, 1, H*W, C_pad]`` (``channels`` = the padded width).""" + hidden = self.hidden(shared.tensor) + out = self.out(hidden) + free_maps(hidden) + return shared.with_tensor(out, self.padded_channels) + + def __call__(self, inputs: Sequence[FeatureMap]) -> FeatureMap: + shared = self.shared_forward(inputs) + out = self.heads_forward(shared) + free_maps(shared) + return out + + def unpack(self, rows: Any, height: int, width: int) -> Dict[str, np.ndarray]: + """Host rows ``[H*W, >= C]`` (a read-back of the head output) -> ``{name: (C_h, H, W)}`` float32.""" + a = np.asarray(rows, dtype=np.float32) + a = a.reshape(-1, a.shape[-1])[: height * width] + return {name: np.ascontiguousarray(a[:, s:e].T.reshape(e - s, height, width)) for name, s, e in self.slices} + + def release(self) -> None: + self.shared.release() + self.hidden.release() + self.out.release() + + def describe(self) -> Dict[str, Any]: + return {"shared": self.shared.describe(), "k_split": self.k_split, "hidden": self.hidden.describe(), + "out": self.out.describe(), "slices": [list(s) for s in self.slices]} + + +def centerhead_numpy(shared: ConvSpec, heads: Sequence[HeadSpec], inputs_nchw: Sequence[Any]) -> Dict[str, np.ndarray]: + """fp32 oracle (torch, the literal graph: concat, conv, six heads) -> ``{"shared": NCHW, name: NCHW}``.""" + import torch + + from .second import _apply_torch + + with torch.no_grad(): + x = torch.cat([torch.as_tensor(np.asarray(t, dtype=np.float32)) for t in inputs_nchw], dim=1) + s = _apply_torch(shared, x) + out = {"shared": s.numpy().copy()} + for name, hidden, final in heads: + out[name] = _apply_torch(final, _apply_torch(hidden, s)).numpy().copy() + return out diff --git a/code/tt_depthpro2/ttaw/models/pillars.py b/code/tt_depthpro2/ttaw/models/pillars.py new file mode 100644 index 0000000000000000000000000000000000000000..30e6f44fef46cccabf172b60321e074b0dad46c0 --- /dev/null +++ b/code/tt_depthpro2/ttaw/models/pillars.py @@ -0,0 +1,479 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C24 companion: the PillarFeatureNet (PFN) of the pillar detectors on the device, and the host staging of its +inputs (PLAN.md section 1.2; CenterPoint, PointPainting, TransFusion). Promoted by the PointPainting port from the +CenterPoint bundle's ``tt/pfn.py`` + ``tt/model.py FrameStaging`` (device-verified there: PFN PCC 0.99997) with the +TransFusion bundle's generalisation (any hidden / output width, pillars of fewer than 32 points); those bundles keep +their copies until they re-vendor. + +The encoder (mmdet3d ``PFNLayer`` x 2 as Autoware exports it; BN folded into both MatMuls by the port's loader): + + h = relu(x @ W0 + b0) x: (P, K, F) decorated points, padded slots all zero h: (P, K, H) + m = max over the K slots of h padded slots included: their rows are relu(b0) + y = max over the slots of relu([h, m] @ W1 + b1) = relu(max_slots(h @ W1a) + m @ W1b + b1) y: (P, O) + +Device form. One pillar is one 32-row tile (its point slots), so a slot max is a tile-column reduction (``ttnn.max`` +over dim -2). Because ``relu(. + c)`` is monotonic, the per-pillar term ``c = m @ W1b + b1`` is added AFTER the max +(exact, also in floating point: rounding is monotonic), so no slot broadcast is needed; two identity blocks fold the +rest into the matmuls (exact: a value times 1.0 with HiFi4 and fp32 accumulation): + + x [P*32, 16] --linear W0 (16 x H_pad) + b0, ReLU--> h [P*32, H_pad] + h --linear Wz = [I_H | W1a] (H_pad x Z)--> z [P*32, Z] = [h | h @ W1a | 0] + z as [P, 32, Z] --max over dim -2--> mz [P, 1, Z] = [m | max(h @ W1a) | 0] + mz --linear Wy = [W1b ; I_O] (Z x O) + b1, ReLU--> y [P, 1, O] + y --untilize, view--> [1, 1, P, O] ROW_MAJOR bf16 rows + +(``H_pad`` = H rounded up to 32, ``Z`` = H + O rounded up to 32, ``O % 32 == 0``: the rows are a C19 gather table.) +The rows feed the gather-form scatter (C19 ``ops.gather.scatter_rows``, which appends the zero sentinel row). + +**Pillars of K < 32 points** (TransFusion: 20): slots K..31 repeat slot 0 (:func:`pack_features`; every kept +pillar has a point in slot 0), so both slot maxima are unchanged (max is idempotent), whereas zero rows there would +add ``relu(b0)`` to the maxima of full pillars. With K = 32 (CenterPoint, PointPainting) the padded slots are the +model's own zero slots. + +**Input**: the host's decorated features as bf16 ROW_MAJOR ``[1, 1, P, 32 * 16]``: one 1 KB row per pillar (32 +slots x F <= 16 features zero-padded to 16). One row per pillar keeps the host-to-device copy at P pages (CenterPoint: +5.1 ms for 40,000 pages of 1 KB vs 32 ms as 1.28 M pages of 32 B); the device reshapes it to ``[1, 1, P*32, 16]`` and +tilizes it. Every pillar row is computed, also past the frame's pillar count (stale or zero input): the scatter index +never points at those rows, so no pillar count reaches the device. :class:`FrameStaging` writes these inputs in place +into persistent host tensors (``tensors.HostStaging``): no per-frame ``from_torch`` of 20 M elements (CenterPoint: 188 +ms) and no allocation; only the kept pillars are converted (torch fp32 -> bf16, RNE). + +**Precision** (``ttaw.precision.Precision``): HiFi4 is required (the identity blocks are exact only with it); fp32 +accumulation; weights per ``Precision.weights`` (fp32: a device "fp32" matmul behaves like TF32, probe P12); +``Precision.activations`` is the dtype of the hidden tensors ``h`` and ``z`` (bf16 by default; fp32 keeps the PFN's +internal roundings off: PointPainting measured on the CPU that the bf16 rounding of ``h`` / ``z`` is the largest PFN +error term, rel. L2 0.0045 vs 0.0017 for the bf16 output rounding alone). The output rows are always bf16 (the +``ttnn.embedding`` table of C19 is bf16-only). + +**Two-term PFN** (``terms=2``; TransFusion's default since its fix rounds 1 / 2, ttaw 0.21.0): every linear is a +:class:`TwoTermLinear` (weights and biases as two bf16 terms ``hi + lo``, fp32 outputs); ``h``, ``z`` and the slot +max stay fp32 and are split into two bf16 terms (:func:`split_terms`) before the next linear; only the output rows +are rounded to bf16. With ``bias_add=True`` (the default) the products are bias-free ``ttnn.matmul`` calls +(:class:`RowMatmul`) and each fp32 bias is added by one exact fp32 ``ttnn.add``: ``ttnn.linear``'s fused bias (also +an all-zero one) rounds the fp32 output to about 11 significant bits on this tree (TransFusion probes T4 / T5). On +TransFusion's golden frames the device PFN output error (relative to fp64 on the same bf16 features) fell from 5.5e-3 +(fused bias) to 2.0e-3 and a 0.48 % heatmap local-max near-tie stayed a local maximum +(``bundles/transfusion-p150/PORT_LOG.md`` "Fix round 1" / "Fix round 2"). Cost: 3 matmuls + 3 adds per linear and +two term splits (P = 65,536: see the TransFusion OPT_BASELINE). ``terms=1`` is the 0.19.0 module unchanged. + +numpy only at import; ttnn / torch are imported inside the device and staging functions. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Dict, Optional + +import numpy as np + +from ..precision import Precision +from .second import RowLinear, free_maps + +__all__ = ["PFN_IN_FEATURES", "PILLAR_SLOTS", "PfnPlan", "TtPillarFeatureNet", "FrameStaging", "features_shape", + "pack_features", "pfn_reference_numpy", "pack_inputs", "DEFAULT_PRECISION", "TWO_TERM_PRECISION", + "split_terms", "RowMatmul", "TwoTermLinear"] + +PFN_IN_FEATURES = 16 # decorated features zero-padded to 16 bf16 = 32-byte slot rows +PILLAR_SLOTS = 32 # one 32-row tile per pillar +TILE = 32 +DEFAULT_PRECISION = "HiFi4+fp32:w=fp32" +TWO_TERM_PRECISION = "HiFi4+fp32:w=bf16" # terms=2: the weight terms are bf16-exact + + +def _round_up(n: int, m: int = TILE) -> int: + return -(-int(n) // m) * m + + +@dataclass(frozen=True) +class PfnPlan: + """The device matrices of the PFN (float32 host arrays; see the module docstring).""" + + w0: np.ndarray # (16, H_pad) + b0: np.ndarray # (H_pad,) + wz: np.ndarray # (H_pad, Z) = [I_H | W1a | 0] + wy: np.ndarray # (Z, O) = [W1b ; I_O ; 0] + b1: np.ndarray # (O,) + in_features: int # F + hidden: int # H (layer-0 width) + out_features: int # O + + @classmethod + def from_weights(cls, w0: Any, b0: Any, w1: Any, b1: Any, *, in_padded: int = PFN_IN_FEATURES) -> "PfnPlan": + """From the BN-folded encoder weights: ``w0`` (F, H) and ``w1`` (2H, O), ``[in, out]`` layout; layer 1 reads + ``concat[h, max_slots h]`` (rows 0..H-1 of ``w1`` act on ``h``, rows H..2H-1 on the max).""" + w0 = np.asarray(w0, np.float32) + w1 = np.asarray(w1, np.float32) + if w0.ndim != 2 or w1.ndim != 2: + raise ValueError(f"w0 {w0.shape} / w1 {w1.shape} must be [in, out] matrices") + f, hdim = w0.shape + out = int(w1.shape[1]) + if w1.shape[0] != 2 * hdim: + raise ValueError(f"w1 {w1.shape} does not take concat[h, max h] of width {2 * hdim}") + if f > in_padded: + raise ValueError(f"{f} features do not fit the {in_padded}-wide slot rows") + if out % TILE: + raise ValueError(f"PFN output width {out}: the C19 gather table needs a multiple of {TILE}") + b0 = np.asarray(b0, np.float32).reshape(-1) + b1 = np.asarray(b1, np.float32).reshape(-1) + if b0.shape != (hdim,) or b1.shape != (out,): + raise ValueError(f"biases {b0.shape} / {b1.shape} do not match widths {hdim} / {out}") + hp, zp = _round_up(hdim), _round_up(hdim + out) + W0 = np.zeros((in_padded, hp), np.float32) + W0[:f, :hdim] = w0 + B0 = np.zeros(hp, np.float32) + B0[:hdim] = b0 + Wz = np.zeros((hp, zp), np.float32) + Wz[:hdim, :hdim] = np.eye(hdim, dtype=np.float32) + Wz[:hdim, hdim:hdim + out] = w1[:hdim] + Wy = np.zeros((zp, out), np.float32) + Wy[:hdim] = w1[hdim:] + Wy[hdim:hdim + out] = np.eye(out, dtype=np.float32) + return cls(W0, B0, Wz, Wy, b1.copy(), int(f), int(hdim), out) + + def forward_numpy(self, features: Any, *, hidden_round: Any = None) -> np.ndarray: + """float32 host emulation of the device graph (``(P, S, F)`` slots -> ``(P, out_features)``); give it the + 32-slot layout of :func:`pack_features` to emulate the device's slots exactly. ``hidden_round``: a function + applied to ``h`` and ``z`` (e.g. a bf16 rounding) to model the hidden dtype.""" + r = hidden_round or (lambda a: a) + x = np.asarray(features, np.float32) + p, slots, f = x.shape + xp = np.zeros((p, slots, self.w0.shape[0]), np.float32) + xp[:, :, :f] = x + h = r(np.maximum(xp @ self.w0 + self.b0, 0.0).astype(np.float32)) + z = r((h @ self.wz).astype(np.float32)) + mz = z.max(axis=1) + return np.maximum(mz @ self.wy + self.b1, 0.0).astype(np.float32) + + +def pfn_reference_numpy(features: Any, w0: Any, b0: Any, w1: Any, b1: Any) -> np.ndarray: + """The literal encoder in float64 (concat form, max over the given slots, padded slots included) -> ``(P, O)`` + float32: the oracle of :class:`PfnPlan` and of the device module.""" + x = np.asarray(features, np.float64) + w0, w1 = np.asarray(w0, np.float64), np.asarray(w1, np.float64) + h = np.maximum(x @ w0 + np.asarray(b0, np.float64), 0.0) + m = h.max(axis=1, keepdims=True) + y = np.maximum(np.concatenate([h, np.broadcast_to(m, h.shape)], axis=2) @ w1 + np.asarray(b1, np.float64), 0.0) + return y.max(axis=1).astype(np.float32) + + +def features_shape(num_pillars: int): + """The device input layout of the PFN: ``(1, 1, num_pillars, 32 * 16)`` (one bf16 row per pillar).""" + return (1, 1, int(num_pillars), PILLAR_SLOTS * PFN_IN_FEATURES) + + +def pack_features(features: Any, num_pillars: int, *, out: Optional[np.ndarray] = None) -> np.ndarray: + """Decorated features ``(P_kept, K, F)`` (K <= 32 point slots, F <= 16; the model's padded slots zero) -> the + device input :func:`features_shape` as float32: features zero-padded to 16, slots K..31 copies of slot 0 when + K < 32 (module docstring), rows past ``P_kept`` zero. ``out`` (an array of that shape) is reused when given.""" + x = np.asarray(features, np.float32) + if x.ndim != 3: + raise ValueError(f"features must be (pillars, slots, features), got {x.shape}") + p, slots, f = x.shape + if slots > PILLAR_SLOTS or f > PFN_IN_FEATURES or p > num_pillars: + raise ValueError(f"features {x.shape} do not fit ({num_pillars}, {PILLAR_SLOTS}, <= {PFN_IN_FEATURES})") + shape = features_shape(num_pillars) + if out is None: + out = np.zeros(shape, np.float32) + elif out.shape != shape or out.dtype != np.float32: + raise ValueError(f"out must be float32 {shape}") + else: + out.fill(0.0) + v = out.reshape(int(num_pillars), PILLAR_SLOTS, PFN_IN_FEATURES) + v[:p, :slots, :f] = x + if 0 < slots < PILLAR_SLOTS: + v[:p, slots:, :f] = x[:, :1, :] + return out + + +def pack_inputs(features: Any, canvas_index: Any, num_pillars: int, *, capacity: int, + features_out: Optional[np.ndarray] = None) -> Dict[str, np.ndarray]: + """The two PFN-graph inputs as numpy (tests and tools; the API uses :class:`FrameStaging`): ``{"features": + (1, 1, capacity, 512) float32, "canvas_index": (1, N) uint32}`` from the kept pillars' features + ``features[:num_pillars]`` and a cell -> pillar-row index (``capacity`` = the zero sentinel row). The index is + range-checked: a bad index would read outside the gather table.""" + from ..ops.gather import check_index + + n = int(num_pillars) + feats = pack_features(np.asarray(features)[:n], capacity, out=features_out) + return {"features": feats, "canvas_index": check_index(canvas_index, num_rows=n, sentinel=capacity)} + + +def split_terms(t: Any): + """An fp32 device tensor -> two bf16 tensors ``hi = bf16(t)``, ``lo = bf16(t - hi)`` (``hi + lo`` carries ~16 + significant bits; the subtraction is exact in fp32). ``t`` is kept.""" + import ttnn + + hi = ttnn.typecast(t, ttnn.bfloat16) + hi32 = ttnn.typecast(hi, ttnn.float32) + diff = ttnn.subtract(t, hi32) + ttnn.deallocate(hi32, False) + lo = ttnn.typecast(diff, ttnn.bfloat16) + ttnn.deallocate(diff, False) + return hi, lo + + +class RowMatmul(RowLinear): + """C24 :class:`RowLinear` without a bias: ``ttnn.matmul`` with an fp32 output, so no bias epilogue touches the fp32 + accumulator (``ttnn.linear``'s fused bias, also an all-zero one, degrades an fp32 output to about 11 significant + bits: TransFusion probes T4 / T5); add the bias afterwards with an exact fp32 ``ttnn.add`` + (:class:`TwoTermLinear` ``bias_add``).""" + + def __init__(self, weight: Any, *, precision: Any, name: str): + super().__init__(weight, None, activation=None, precision=precision, output_dtype="float32", name=name) + + def __call__(self, x: Any) -> Any: + import ttnn + + if int(x.shape[-1]) != self.in_channels: + raise ValueError(f"{self.name}: input has {int(x.shape[-1])} channels, expected {self.in_channels}") + weight, _, grid, cfg = self._device or self._upload(x.device()) + return ttnn.matmul(x, weight, compute_kernel_config=cfg, core_grid=grid, memory_config=ttnn.DRAM_MEMORY_CONFIG, + dtype=ttnn.float32) + + +class TwoTermLinear: + """``y = act(x @ W + b)`` on a two-term input ``x = hi + lo`` (bf16 TILE tensors ``[..., R, K]``; ``lo`` may be + None for a bf16 input) with ``W`` and ``b`` as two bf16 terms: ``hi @ W_hi``, ``hi @ W_lo`` and ``lo @ W_hi`` + (bf16 x bf16 products, exact under HiFi4, fp32 accumulation and fp32 outputs) summed in fp32, the activation in + fp32. Returns the fp32 TILE tensor (DRAM); the inputs are kept. The dropped ``lo @ W_lo`` term is ~2^-16 + relative. Identity blocks in ``W`` stay exact (1.0 is a bf16 hi term). + + ``bias_add=True`` (default): the three products are bias-free :class:`RowMatmul` calls and the fp32 bias is added + by one exact fp32 ``ttnn.add`` (with the ReLU); ``bias_add=False``: three C24 :class:`RowLinear` with the bias + terms fused into the matmuls, whose epilogue rounds the fp32 output to about 11 significant bits.""" + + def __init__(self, weight: Any, bias: Any = None, *, activation: Optional[str] = None, + precision: Any = TWO_TERM_PRECISION, name: str = "linear", bias_add: bool = True): + from ..tensors import round_to_bf16 + + prec = Precision.parse(precision) + if prec.weights != "bfloat16" or prec.fidelity != "HiFi4" or not prec.fp32_acc: + raise ValueError(f"{name}: two-term linears need HiFi4, fp32 accumulation and bf16 weight terms, got " + f"{prec.label}") + w = np.asarray(weight, np.float32) + wh = round_to_bf16(w) + wl = round_to_bf16(w - wh) + b = np.zeros(w.shape[1], np.float32) if bias is None else np.asarray(bias, np.float32).reshape(-1) + if activation not in (None, "relu"): + raise ValueError(f"{name}: activation {activation!r}: None or 'relu'") + self.name = name + self.activation = activation + self.in_channels, self.out_channels = (int(n) for n in w.shape) + self.precision = prec + self.bias_add = bool(bias_add) + self._bias = None + if self.bias_add: + self.main = RowMatmul(wh, precision=prec, name=f"{name}.hi") + self.corr = RowMatmul(wl, precision=prec, name=f"{name}.wlo") + self.low = self.main # lo @ W_hi: the same device weights + self.bias_host = b.reshape(1, -1).copy() + else: + bh = round_to_bf16(b) + bl = round_to_bf16(b - bh) + self.main = RowLinear(wh, bh, precision=prec, output_dtype="float32", name=f"{name}.hi") + self.corr = RowLinear(wl, bl, precision=prec, output_dtype="float32", name=f"{name}.wlo") + self.low = RowLinear(wh, None, precision=prec, output_dtype="float32", name=f"{name}.lo") + + def _bias_tensor(self, device: Any) -> Any: + import torch + import ttnn + + if self._bias is None: + self._bias = ttnn.from_torch(torch.from_numpy(self.bias_host), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, + device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) + return self._bias + + def __call__(self, hi: Any, lo: Any = None) -> Any: + import ttnn + + from ..ops.conv import unary_with_param + + relu = [unary_with_param("relu")] if self.activation else [] + if self.bias_add: + bias = self._bias_tensor(hi.device()) + y = self.corr(hi) # the small terms first, then the main product + if lo is not None: + c = self.low(lo) + y2 = ttnn.add(y, c, memory_config=ttnn.DRAM_MEMORY_CONFIG) + free_maps(y, c) + y = y2 + a = self.main(hi) + y2 = ttnn.add(a, y, memory_config=ttnn.DRAM_MEMORY_CONFIG) + free_maps(a, y) + y = ttnn.add(y2, bias, activations=relu, memory_config=ttnn.DRAM_MEMORY_CONFIG) + free_maps(y2) + return y + a = self.main(hi) + b = self.corr(hi) + last = lo is None + y = ttnn.add(a, b, activations=relu if last else [], memory_config=ttnn.DRAM_MEMORY_CONFIG) + free_maps(a, b) + if lo is not None: + c = self.low(lo) + y2 = ttnn.add(y, c, activations=relu, memory_config=ttnn.DRAM_MEMORY_CONFIG) + free_maps(y, c) + y = y2 + return y + + def release(self) -> None: + for layer in {id(m): m for m in (self.main, self.corr, self.low)}.values(): + layer.release() + if self._bias is not None: + free_maps(self._bias) + self._bias = None + + def describe(self) -> Dict[str, Any]: + return {"name": self.name, "terms": 2, "cin": self.in_channels, "cout": self.out_channels, + "activation": self.activation, "precision": self.precision.label, "output_dtype": "float32", + "bias": "fp32 add" if self.bias_add else "fused"} + + +class TtPillarFeatureNet: + """The PFN on ``num_pillars`` pillars: ``[1, 1, P, 32*16]`` bf16 ROW_MAJOR -> ``[1, 1, P, O]`` bf16 ROW_MAJOR + rows (module docstring). ``precision``: a :class:`..precision.Precision` or its spec; its ``activations`` dtype is + that of the hidden tensors ``h`` / ``z`` (``terms=1``). ``terms=2``: the two-term PFN (module docstring; needs + ``w=bf16``, e.g. :data:`TWO_TERM_PRECISION`; hidden tensors fp32), ``bias_add`` as in :class:`TwoTermLinear`.""" + + def __init__(self, plan: PfnPlan, *, num_pillars: int, precision: Any = DEFAULT_PRECISION, name: str = "pfn", + terms: int = 1, bias_add: bool = True): + self.plan = plan + self.name = name + self.num_pillars = int(num_pillars) + self.terms = int(terms) + if self.terms not in (1, 2): + raise ValueError(f"{name}: terms must be 1 or 2, got {terms}") + self.precision = Precision.parse(precision) + if self.precision.fidelity != "HiFi4": + raise ValueError(f"{name}: the PFN identity blocks are exact only with HiFi4 (x * 1.0)") + self.bias_add = bool(bias_add) + if self.terms == 2: + kw = dict(precision=self.precision, bias_add=self.bias_add) + self.l0: Any = TwoTermLinear(plan.w0, plan.b0, activation="relu", name=f"{name}.l0", **kw) + self.lz: Any = TwoTermLinear(plan.wz, None, name=f"{name}.lz", **kw) + self.ly: Any = TwoTermLinear(plan.wy, plan.b1, activation="relu", name=f"{name}.ly", **kw) + else: + hidden = self.precision.activations + self.l0 = RowLinear(plan.w0, plan.b0, activation="relu", precision=self.precision, output_dtype=hidden, + name=f"{name}.l0") + self.lz = RowLinear(plan.wz, None, precision=self.precision, output_dtype=hidden, name=f"{name}.lz") + self.ly = RowLinear(plan.wy, plan.b1, activation="relu", precision=self.precision, + output_dtype="bfloat16", name=f"{name}.ly") + self.out_features = plan.out_features + + @property + def features_shape(self): + return features_shape(self.num_pillars) + + def __call__(self, features_rm: Any) -> Any: + import ttnn + + p = self.num_pillars + rows = ttnn.reshape(features_rm, (1, 1, p * PILLAR_SLOTS, PFN_IN_FEATURES)) # 1 KB rows -> 32 B slot rows + x = ttnn.to_layout(rows, ttnn.TILE_LAYOUT) # [1, 1, P*32, 16] + free_maps(rows) + if self.terms == 2: + y = self._two_term(x) + else: + h = self.l0(x) # [1, 1, P*32, H_pad] + free_maps(x) + z = self.lz(h) # [1, 1, P*32, Z] + free_maps(h) + z4 = ttnn.reshape(z, (1, p, PILLAR_SLOTS, int(z.shape[-1]))) # one pillar = one tile row block (a view) + mz = ttnn.max(z4, dim=2, keepdim=True) # [1, P, 1, Z] + free_maps(z) + y = self.ly(mz) # [1, P, 1, O] bf16 + free_maps(mz) + y_rm = ttnn.to_layout(y, ttnn.ROW_MAJOR_LAYOUT) + free_maps(y) + return ttnn.reshape(y_rm, (1, 1, p, self.out_features)) + + def _two_term(self, x: Any) -> Any: + """``terms=2``: fp32 ``h`` / ``z`` / slot max, each split into two bf16 terms for the next linear -> bf16 + ``[1, P, 1, O]`` (TILE).""" + import ttnn + + p = self.num_pillars + h = self.l0(x) # fp32 [1, 1, P*32, H_pad] + free_maps(x) + hh, hl = split_terms(h) + free_maps(h) + z = self.lz(hh, hl) # fp32 [1, 1, P*32, Z] + free_maps(hh, hl) + z4 = ttnn.reshape(z, (1, p, PILLAR_SLOTS, int(z.shape[-1]))) + mz = ttnn.max(z4, dim=2, keepdim=True) # fp32 [1, P, 1, Z] + free_maps(z) + mh, ml = split_terms(mz) + free_maps(mz) + y32 = self.ly(mh, ml) # fp32 [1, P, 1, O] + free_maps(mh, ml) + y = ttnn.typecast(y32, ttnn.bfloat16) + free_maps(y32) + return y + + def release(self) -> None: + for layer in (self.l0, self.lz, self.ly): + layer.release() + + def describe(self) -> Dict[str, Any]: + return {"name": self.name, "num_pillars": self.num_pillars, "in_features": self.plan.in_features, + "hidden": self.plan.hidden, "out": self.plan.out_features, "z_width": int(self.plan.wz.shape[1]), + "slots": PILLAR_SLOTS, "precision": self.precision.label, "terms": self.terms, + "hidden_dtype": "float32" if self.terms == 2 else self.precision.activations, + **({"bias": "fp32 add" if self.bias_add else "fused"} if self.terms == 2 else {})} + + +class FrameStaging: + """Persistent host buffers of the two PFN-graph inputs: bf16 ``features`` (:func:`features_shape`) and uint32 + ``canvas_index`` ``[1, num_cells]`` (``tensors.HostStaging``: the ttnn host tensor's own memory, written in + place). :meth:`write` converts only the kept pillars (torch fp32 -> bf16, RNE) into their rows (slots K..31 = + slot 0 when K < 32), zeroes the rows the previous frame used beyond them, copies the range-checked index, and + returns the ``TraceRunner`` inputs (host tensors, uploaded as they are). Without a zero-copy alias (another + tt-metal build) it falls back to :func:`pack_features` + ``HostStaging.write`` (same values).""" + + def __init__(self, num_pillars: int, num_cells: int): + from ..tensors import HostStaging + + self.num_pillars = int(num_pillars) + self.num_cells = int(num_cells) + self.features = HostStaging(features_shape(self.num_pillars), "bfloat16") + self.index = HostStaging((1, self.num_cells), "uint32") + self._used = self.num_pillars # rows that may hold data (all, until the first write) + + @property + def zero_copy(self) -> bool: + return bool(self.features.zero_copy and self.index.zero_copy) + + def write(self, features: Any, canvas_index: Any, num_pillars: Optional[int] = None) -> Dict[str, Any]: + """``features``: ``(P, K, F)`` float32 decorated pillars (only the first ``num_pillars`` rows are used; + default all); ``canvas_index``: ``num_cells`` entries in ``[0, num_pillars)`` or the sentinel + ``self.num_pillars``.""" + from ..ops.gather import check_index + + f_all = np.asarray(features) + p = int(f_all.shape[0] if num_pillars is None else num_pillars) + if p > self.num_pillars: + raise ValueError(f"{p} pillars exceed the staging capacity {self.num_pillars}") + feats = np.asarray(f_all[:p], np.float32) + index = check_index(canvas_index, num_rows=p, sentinel=self.num_pillars) + if index.size != self.num_cells: + raise ValueError(f"canvas index of {index.size} cells, expected {self.num_cells}") + if not self.zero_copy: # no host alias: plain writes + return {"features": self.features.write(pack_features(feats, self.num_pillars)), + "canvas_index": self.index.write(index)} + import torch + + if feats.ndim != 3 or feats.shape[1] > PILLAR_SLOTS or feats.shape[2] > PFN_IN_FEATURES: + raise ValueError(f"features {feats.shape} do not fit (P, <= {PILLAR_SLOTS}, <= {PFN_IN_FEATURES})") + view = self.features.view.reshape(self.num_pillars, PILLAR_SLOTS, PFN_IN_FEATURES).view(np.int16) + dst = torch.from_numpy(view) + slots, f = feats.shape[1], feats.shape[2] + src = torch.from_numpy(np.ascontiguousarray(feats)).to(torch.bfloat16).view(torch.int16) + dst[:p, :slots, :f] = src + if f < PFN_IN_FEATURES: + dst[:p, :, f:] = 0 + if 0 < slots < PILLAR_SLOTS: + dst[:p, slots:, :f] = src[:, :1, :] + if p < self._used: + dst[p:self._used] = 0 + self._used = p + self.index.view[...] = index + return {"features": self.features.tensor, "canvas_index": self.index.tensor} diff --git a/code/tt_depthpro2/ttaw/models/resnet.py b/code/tt_depthpro2/ttaw/models/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..c264e6bc87ad4ef00c0686b9bc925d5d283435a4 --- /dev/null +++ b/code/tt_depthpro2/ttaw/models/resnet.py @@ -0,0 +1,271 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C27: ResNet builders on device feature maps, cameras as batch (PLAN.md section 1.2 row C27; first built by the +BEVDet port for its ResNet-50 image backbone and CustomResNet BEV encoder; BEVFormer and METEOR reuse it). + +- :class:`Bottleneck`: ResNet-50/101, pytorch style (the stride sits on the 3x3 ``conv2``; 1x1 projection + ``downsample`` on the first block of a stage): ``relu(conv3(relu(conv2(relu(conv1(x))))) + idt)``; +- :class:`BasicBlock`: ResNet-18/34 and BEVDet's CustomResNet (two 3x3 convs; the projection may be any conv, + CustomResNet's is a 3x3 stride-2 one): ``relu(conv2(relu(conv1(x))) + idt)``; +- :class:`ResNetStem`: ``maxpool 3x3 s2 p1 (relu(conv1 7x7 s2 p3))`` (the max pool runs DRAM-sliced); +- :class:`ResNetStages`: ``len(layers)`` stages of one block kind; ``__call__(x, keep=...)`` returns the stage + outputs a caller wants (FPN levels, taps) and frees the others as soon as the next stage consumed them. + +**Weights** come from a parameter provider ``provider(module) -> ConvParams`` (BatchNorm folded, conv attributes as +the source graph defines them: BEVDet's reads ``OnnxWeights`` by consuming node, so no kernel size or stride is +re-typed here). **Names** come from a ``names(stage, block)`` callable: :func:`mmdet_names` (``layer1.0.conv1``, +``downsample.0``) and :func:`custom_resnet_names` (``layers.0.0.conv1``, ``downsample``). **Convs** come from a +``factory(module, params, activation)`` (default :func:`conv_factory`: one C17 ``Conv2d`` per module, with a +``ttaw.precision`` spec or a ``PrecisionPolicy`` resolved per module name); a port that needs deformable convs +(BEVFormer / METEOR DCN, PLAN.md C23 / C27 "DCN hook") returns its own callable for the modules it names. + +Placement: every activation is a DRAM-interleaved TILE ``[1, 1, N*H*W, C]`` map (C17's rule: DRAM inputs run ttnn's +automatic DRAM slicing, 1x1 convs are matmuls placed back in DRAM), so the 6 x 256 x 704 cameras' 34.6 MB stem and +layer1 maps fit; intermediates are freed as soon as they are consumed. Every op is traceable; a layer prepares its +weights on its first (eager) call. :func:`resnet_numpy` is the fp32 torch oracle of the same blocks. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import numpy as np + +from ..ops.conv import CONV_PRECISION, Conv2d, FeatureMap, residual_add +from ..precision import Precision, PrecisionPolicy + +__all__ = ["ConvParams", "DEFAULT_PRECISION", "conv_factory", "mmdet_names", "custom_resnet_names", "Bottleneck", + "BasicBlock", "ResNetStem", "ResNetStages", "maxpool_out_hw", "resnet_numpy", "identity_like"] + +DEFAULT_PRECISION = CONV_PRECISION + + +@dataclass(frozen=True) +class ConvParams: + """One BN-folded convolution as a provider returns it (numpy float32).""" + + weight: np.ndarray # [Cout, Cin / groups, kh, kw] + bias: Optional[np.ndarray] = None # [Cout] + stride: Tuple[int, int] = (1, 1) + padding: Tuple[int, int, int, int] = (0, 0, 0, 0) # top, bottom, left, right + dilation: Tuple[int, int] = (1, 1) + groups: int = 1 + + +Provider = Callable[[str], ConvParams] +ConvFactory = Callable[[str, ConvParams, Optional[str]], Callable[[FeatureMap], FeatureMap]] +Names = Callable[[int, int], Dict[str, str]] + + +def conv_factory(precision: Union[str, Precision, PrecisionPolicy] = DEFAULT_PRECISION, **conv_kwargs: Any + ) -> ConvFactory: + """The standard factory: one C17 ``Conv2d`` per module. ``precision``: a spec / :class:`Precision` for every + conv, or a :class:`PrecisionPolicy` resolved per module name; other keywords go to every ``Conv2d``.""" + + def make(module: str, p: ConvParams, activation: Optional[str]) -> Conv2d: + prec = precision.resolve(module) if isinstance(precision, PrecisionPolicy) else precision + return Conv2d(p.weight, p.bias, stride=p.stride, padding=p.padding, dilation=p.dilation, groups=p.groups, + activation=activation, precision=prec, name=module, **conv_kwargs) + + return make + + +def mmdet_names(prefix: str) -> Names: + """mmdet / torchvision names: ``{prefix}.layer{stage + 1}.{block}.conv{1,2,3}`` and ``.downsample.0``.""" + + def names(stage: int, block: int) -> Dict[str, str]: + p = f"{prefix}.layer{stage + 1}.{block}" + return {"conv1": p + ".conv1", "conv2": p + ".conv2", "conv3": p + ".conv3", + "downsample": p + ".downsample.0", "block": p} + + return names + + +def custom_resnet_names(prefix: str) -> Names: + """BEVDet CustomResNet names: ``{prefix}.layers.{stage}.{block}.conv{1,2}`` and ``.downsample``.""" + + def names(stage: int, block: int) -> Dict[str, str]: + p = f"{prefix}.layers.{stage}.{block}" + return {"conv1": p + ".conv1", "conv2": p + ".conv2", "downsample": p + ".downsample", "block": p} + + return names + + +def identity_like(x: FeatureMap, like: FeatureMap) -> FeatureMap: + """The identity shortcut ``x`` in the tensor shape of the residual branch output ``like`` (same rows and + channels). ``ttnn.max_pool2d`` on a DRAM input (:class:`ResNetStem`) returns a 4-D ``[N, OH, OW, C]`` TILE map + (``generic_pools.cpp`` ``pool2d_DRAM``) while a conv returns the flattened ``[1, 1, N*OH*OW, C]`` rows, and + ``ttnn.add`` of the two raises ``Invalid subtile broadcast type``: the first block of a ResNet-18 / 34 stage 1 (no + projection) adds the stem output itself (METEOR port, ttaw 0.17.2). A no-op when the shapes already agree.""" + if tuple(x.tensor.shape) == tuple(like.tensor.shape): + return x + import ttnn + + return x.with_tensor(ttnn.reshape(x.tensor, tuple(like.tensor.shape))) + + +class Bottleneck: + """``relu(conv3(relu(conv2(relu(conv1(x))))) + idt)``; ``idt = downsample(x)`` when the block has a projection.""" + + def __init__(self, provider: Provider, names: Dict[str, str], *, has_downsample: bool, factory: ConvFactory): + self.name = names["block"] + self.conv1 = factory(names["conv1"], provider(names["conv1"]), "relu") + self.conv2 = factory(names["conv2"], provider(names["conv2"]), "relu") + self.conv3 = factory(names["conv3"], provider(names["conv3"]), None) + self.downsample = (factory(names["downsample"], provider(names["downsample"]), None) + if has_downsample else None) + + def __call__(self, x: FeatureMap) -> FeatureMap: + y = self.conv1(x) + z = self.conv2(y) + y.deallocate() + y = self.conv3(z) + z.deallocate() + if self.downsample is not None: + idt = self.downsample(x) + out = residual_add(y, idt, "relu") + idt.deallocate() + else: + out = residual_add(y, identity_like(x, y), "relu") + y.deallocate() + return out + + def convs(self) -> List[Any]: + return [c for c in (self.conv1, self.conv2, self.conv3, self.downsample) if c is not None] + + +class BasicBlock: + """``relu(conv2(relu(conv1(x))) + idt)``; ``idt = downsample(x)`` when the block has a projection.""" + + def __init__(self, provider: Provider, names: Dict[str, str], *, has_downsample: bool, factory: ConvFactory): + self.name = names["block"] + self.conv1 = factory(names["conv1"], provider(names["conv1"]), "relu") + self.conv2 = factory(names["conv2"], provider(names["conv2"]), None) + self.downsample = (factory(names["downsample"], provider(names["downsample"]), None) + if has_downsample else None) + + def __call__(self, x: FeatureMap) -> FeatureMap: + y = self.conv1(x) + z = self.conv2(y) + y.deallocate() + if self.downsample is not None: + idt = self.downsample(x) + out = residual_add(z, idt, "relu") + idt.deallocate() + else: + out = residual_add(z, identity_like(x, z), "relu") + z.deallocate() + return out + + def convs(self) -> List[Any]: + return [c for c in (self.conv1, self.conv2, self.downsample) if c is not None] + + +def maxpool_out_hw(h: int, w: int, k: int = 3, s: int = 2, p: int = 1) -> Tuple[int, int]: + return (h + 2 * p - k) // s + 1, (w + 2 * p - k) // s + 1 + + +class ResNetStem: + """``maxpool 3x3 s2 p1 (relu(conv1))`` (``conv_module`` names the stem conv; ``pool=False`` skips the pool). + The max pool reads the DRAM conv output with automatic DRAM slicing and writes a TILE map for the first block; + on that DRAM path its tensor is 4-D ``[N, OH, OW, C]`` (not the flattened rows of a conv output): convs take it + as is, and the blocks' identity shortcuts reshape it (:func:`identity_like`).""" + + def __init__(self, provider: Provider, conv_module: str, *, factory: Optional[ConvFactory] = None, + pool: bool = True): + factory = factory or conv_factory() + self.conv1 = factory(conv_module, provider(conv_module), "relu") + self.pool = bool(pool) + + def __call__(self, x: FeatureMap) -> FeatureMap: + import ttnn + + y = self.conv1(x) + if not self.pool: + return y + out = ttnn.max_pool2d(y.tensor, batch_size=y.batch, input_h=y.height, input_w=y.width, + channels=y.channels, kernel_size=[3, 3], stride=[2, 2], padding=[1, 1], + dilation=[1, 1], ceil_mode=False, memory_config=ttnn.DRAM_MEMORY_CONFIG, + output_layout=ttnn.TILE_LAYOUT) + y.deallocate() + oh, ow = maxpool_out_hw(y.height, y.width) + return FeatureMap(out, y.batch, oh, ow, y.channels) + + def convs(self) -> List[Any]: + return [self.conv1] + + +class ResNetStages: + """``len(layers)`` stages of ``block`` (``"bottleneck"`` or ``"basic"``); block 0 of stage s has the projection + when ``downsample_first[s]`` (default: every stage). ``__call__(x, keep)`` returns the outputs of the stages in + ``keep`` (others are freed once consumed; ``x`` itself is freed only with ``free_input=True``).""" + + def __init__(self, provider: Provider, names: Names, layers: Sequence[int], *, block: str = "bottleneck", + factory: Optional[ConvFactory] = None, downsample_first: Sequence[bool] = ()): + if block not in ("bottleneck", "basic"): + raise ValueError("block must be 'bottleneck' or 'basic'") + factory = factory or conv_factory() + cls = Bottleneck if block == "bottleneck" else BasicBlock + ds = list(downsample_first) or [True] * len(layers) + if len(ds) != len(layers): + raise ValueError("downsample_first needs one entry per stage") + self.block = block + self.stages: List[List[Any]] = [] + for s, n in enumerate(layers): + self.stages.append([cls(provider, names(s, b), has_downsample=(b == 0 and bool(ds[s])), factory=factory) + for b in range(int(n))]) + + def __call__(self, x: FeatureMap, keep: Sequence[int] = (), *, free_input: bool = False) -> List[FeatureMap]: + outs: List[FeatureMap] = [] + cur = x + for s, blocks in enumerate(self.stages): + for blk in blocks: + nxt = blk(cur) + if (cur is not x or free_input) and not any(cur is o for o in outs): + cur.deallocate() + cur = nxt + if s in keep: + outs.append(cur) + if cur is not x and not any(cur is o for o in outs): + cur.deallocate() + return outs + + def convs(self) -> List[Any]: + return [c for blocks in self.stages for blk in blocks for c in blk.convs()] + + +def resnet_numpy(x: np.ndarray, provider: Provider, names: Names, layers: Sequence[int], *, + block: str = "bottleneck", stem: Optional[str] = None, keep: Sequence[int] = (), + downsample_first: Sequence[bool] = ()) -> List[np.ndarray]: + """fp32 torch oracle of :class:`ResNetStem` (if ``stem`` names its conv) + :class:`ResNetStages` on an NCHW + array -> the kept stage outputs (NCHW float32).""" + import torch + import torch.nn.functional as F + + def conv(t, module, relu): + p = provider(module) + top, bottom, left, right = p.padding + t = F.pad(t, (left, right, top, bottom)) + y = F.conv2d(t, torch.from_numpy(np.asarray(p.weight, np.float32)), + None if p.bias is None else torch.from_numpy(np.asarray(p.bias, np.float32)), + stride=tuple(p.stride), dilation=tuple(p.dilation), groups=p.groups) + return torch.relu(y) if relu else y + + ds = list(downsample_first) or [True] * len(layers) + outs = [] + with torch.no_grad(): + t = torch.from_numpy(np.asarray(x, np.float32)) + if stem is not None: + t = F.max_pool2d(conv(t, stem, True), 3, 2, 1) + for s, n in enumerate(layers): + for b in range(int(n)): + nm = names(s, b) + idt = conv(t, nm["downsample"], False) if (b == 0 and ds[s]) else t + y = conv(t, nm["conv1"], True) + if block == "bottleneck": + y = conv(conv(y, nm["conv2"], True), nm["conv3"], False) + else: + y = conv(y, nm["conv2"], False) + t = torch.relu(y + idt) + if s in keep: + outs.append(t.numpy()) + return outs diff --git a/code/tt_depthpro2/ttaw/models/second.py b/code/tt_depthpro2/ttaw/models/second.py new file mode 100644 index 0000000000000000000000000000000000000000..3043a62778faa2925e4f44311e641f3ef7e738b5 --- /dev/null +++ b/code/tt_depthpro2/ttaw/models/second.py @@ -0,0 +1,311 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C24: SECOND backbone + SECONDFPN neck on the device (PLAN.md section 1.2 row C24; CenterPoint, PointPainting, +TransFusion and BEVFusion use them), built from BN-folded host weights on the C17 builders (``ttaw.ops.conv``). + +- :class:`Second`: blocks of 3x3 conv (zero padding 1) + ReLU; the first conv of a block carries the block stride + (mmdet3d ``SECOND``: ``layer_strides`` [1, 2, 2], CenterPoint-tiny [2, 2, 2]). Returns every block output. +- :class:`SecondFPN`: one deblock per block output, each up-sampling to the same grid, + ReLU (mmdet3d + ``SECONDFPN``): a ``"conv"`` deblock is a 1x1 stride-1 conv (a :class:`RowLinear`), a ``"conv_transpose"`` deblock + a ConvTranspose with kernel == stride (k = 1 a :class:`RowLinear`, k = 2 ``ttnn.conv_transpose2d``, k >= 3 + linear + depth-to-space: C17 ``ConvTranspose2d``, probe P5). The concat of the deblock outputs is NOT built: the + consumer takes the list (C25's K-split shared conv reads the parts, so CenterPoint's 177 MB concat never exists). + +Placement: every module output is a DRAM interleaved TILE ``[1, 1, N*H*W, C]`` map (the robust first-port layout: +3x3 convs on DRAM inputs run ttnn's automatic DRAM slicing, probe P14; L1 residency is optimization work). +Precision: :data:`DEFAULT_PRECISION` (C17's ``CONV_PRECISION``, HiFi4 + fp32 accumulation + packer L1 +accumulation: without it a conv keeps its partial sums in bf16 between inner blocks) unless a +``ttaw.precision.PrecisionPolicy`` says otherwise for ``.block.conv`` / ``.deblock``; a +precision's ``activations`` dtype (``:a=fp32``) is the dtype of that layer's OUTPUT (bf16 by default), the knob of a +deep plain conv stack whose bf16 activation rounding compounds (S:centerpoint:396-408). + +:class:`ConvSpec` records are plain numpy, so a port maps its own weight loader onto them; :func:`second_numpy` / +:func:`second_fpn_numpy` are the fp32 torch oracles of the device modules. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Sequence + +import numpy as np + +from ..ops.conv import CONV_PRECISION, Conv2d, ConvTranspose2d, FeatureMap, is_dram +from ..precision import Precision, PrecisionPolicy + +__all__ = ["ConvSpec", "RowLinear", "Second", "SecondFPN", "DEFAULT_PRECISION", "default_policy", "second_numpy", + "second_fpn_numpy", "free_maps"] + +DEFAULT_PRECISION = CONV_PRECISION + + +@dataclass(frozen=True) +class ConvSpec: + """One conv layer with BN folded: ``y = relu?(conv(x, weight) + bias)``. + + ``kind="conv"``: weight ``[Cout, Cin, k, k]``; ``kind="conv_transpose"``: weight ``[Cin, Cout, s, s]`` (kernel == + stride, no padding). ``padding`` None = ``k // 2`` for convs.""" + + weight: np.ndarray + bias: Optional[np.ndarray] + stride: int = 1 + padding: Optional[int] = None + relu: bool = True + kind: str = "conv" + name: str = "" + + @property + def kernel(self) -> int: + return int(np.shape(self.weight)[-1]) + + @property + def in_channels(self) -> int: + return int(np.shape(self.weight)[1 if self.kind == "conv" else 0]) + + @property + def out_channels(self) -> int: + return int(np.shape(self.weight)[0 if self.kind == "conv" else 1]) + + +def default_policy() -> PrecisionPolicy: + """:data:`DEFAULT_PRECISION` everywhere (bf16 weights).""" + return PrecisionPolicy(default=DEFAULT_PRECISION) + + +def free_maps(*maps: Any) -> None: + """Deallocate device feature maps / tensors that still hold their buffer (``force=False``: memory shared with + a view or another owner is left alone; ``ttnn.deallocate`` forces by default, probe P2).""" + import ttnn + + for m in maps: + t = m.tensor if isinstance(m, FeatureMap) else m + if t is not None and t.is_allocated(): + ttnn.deallocate(t, False) + + +def _to_dram(fm: FeatureMap) -> FeatureMap: + """The map in DRAM (moved to DRAM interleaved when an op left it in L1, e.g. ``conv_transpose2d``'s sharded + output; a no-op for DRAM maps).""" + import ttnn + + if is_dram(fm.tensor): + return fm + out = fm.with_tensor(ttnn.to_memory_config(fm.tensor, ttnn.DRAM_MEMORY_CONFIG)) + free_maps(fm) + return out + + +class RowLinear: + """``y = act(x @ W + b)`` on the rows of a feature map (a 1x1 stride-1 conv): ``[1, 1, R, K]`` TILE -> + ``[1, 1, R, N]`` TILE in DRAM, through ``ttnn.linear`` with an explicit compute config and the device grid as + ``core_grid`` (which keeps the activation fused in the matmul). ``weight``: ``[K, N]`` (in, out) or a 1x1 conv + weight ``[N, K, 1, 1]``. Device weights are uploaded by the first call (outside any capture).""" + + def __init__(self, weight: Any, bias: Any = None, *, activation: Optional[str] = None, + precision: Any = DEFAULT_PRECISION, output_dtype: str = "bfloat16", name: str = "linear"): + w = np.asarray(weight, dtype=np.float32) + if w.ndim == 4: + if w.shape[2:] != (1, 1): + raise ValueError(f"{name}: a conv weight must be 1x1, got {w.shape}") + w = w[:, :, 0, 0].T + if w.ndim != 2: + raise ValueError(f"{name}: weight must be [K, N], got {w.shape}") + if activation not in (None, "relu"): + raise ValueError(f"{name}: activation {activation!r}: None or 'relu'") + self.name = name + self.weight_host = np.ascontiguousarray(w) + self.in_channels, self.out_channels = (int(s) for s in w.shape) + b = np.zeros(self.out_channels, np.float32) if bias is None else np.asarray(bias, np.float32) + if b.shape != (self.out_channels,): + raise ValueError(f"{name}: bias must be ({self.out_channels},), got {b.shape}") + if not (np.all(np.isfinite(w)) and np.all(np.isfinite(b))): + raise ValueError(f"{name}: non-finite weights") + self.bias_host = b + self.activation = activation + self.precision = Precision.parse(precision) + self.output_dtype = output_dtype + self._device: Optional[tuple] = None + + def _upload(self, device: Any): + import torch + import ttnn + + from ..tensors import ttnn_dtype + + wdt = ttnn_dtype(self.precision.weights) + bdt = ttnn.bfloat16 if wdt == ttnn.bfloat8_b else wdt + g = device.compute_with_storage_grid_size() + self._device = ( + ttnn.from_torch(torch.from_numpy(self.weight_host), dtype=wdt, layout=ttnn.TILE_LAYOUT, device=device, + memory_config=ttnn.DRAM_MEMORY_CONFIG), + ttnn.from_torch(torch.from_numpy(self.bias_host.reshape(1, -1)), dtype=bdt, layout=ttnn.TILE_LAYOUT, + device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG), + ttnn.CoreGrid(y=int(g.y), x=int(g.x)), + self.precision.compute_kernel_config()) + return self._device + + def __call__(self, x: Any) -> Any: + """``x``: a TILE device tensor ``[..., R, K]`` or a :class:`FeatureMap` (returned as one).""" + import ttnn + + from ..tensors import ttnn_dtype + + t = x.tensor if isinstance(x, FeatureMap) else x + if int(t.shape[-1]) != self.in_channels: + raise ValueError(f"{self.name}: input has {int(t.shape[-1])} channels, expected {self.in_channels}") + weight, bias, grid, cfg = self._device or self._upload(t.device()) + y = ttnn.linear(t, weight, bias=bias, activation=self.activation, compute_kernel_config=cfg, core_grid=grid, + memory_config=ttnn.DRAM_MEMORY_CONFIG, dtype=ttnn_dtype(self.output_dtype)) + return x.with_tensor(y, self.out_channels) if isinstance(x, FeatureMap) else y + + def release(self) -> None: + if self._device is not None: + free_maps(self._device[0], self._device[1]) + self._device = None + + def describe(self) -> Dict[str, Any]: + return {"name": self.name, "cin": self.in_channels, "cout": self.out_channels, "activation": self.activation, + "precision": self.precision.label, "output_dtype": self.output_dtype} + + +def _precision(policy: Optional[PrecisionPolicy], name: str) -> Precision: + return policy.resolve(name) if policy is not None else Precision.parse(DEFAULT_PRECISION) + + +class Second: + """SECOND backbone: ``blocks[i]`` is the list of :class:`ConvSpec` of block ``i`` (k x k convs, BN folded).""" + + def __init__(self, blocks: Sequence[Sequence[ConvSpec]], *, policy: Optional[PrecisionPolicy] = None, + prefix: str = "backbone"): + self.prefix = prefix + self.blocks: List[List[Conv2d]] = [] + for i, block in enumerate(blocks): + layers = [] + for j, spec in enumerate(block): + if spec.kind != "conv": + raise ValueError(f"{prefix}.block{i}.conv{j}: SECOND layers are convs, got {spec.kind}") + name = f"{prefix}.block{i}.conv{j}" + pad = spec.kernel // 2 if spec.padding is None else int(spec.padding) + prec = _precision(policy, name) + layers.append(Conv2d(spec.weight, spec.bias, stride=spec.stride, padding=pad, + activation="relu" if spec.relu else None, precision=prec, + output_dtype=prec.activations, name=name)) + self.blocks.append(layers) + + def out_shapes(self, height: int, width: int) -> List[tuple]: + """``(H, W, C)`` of every block output for an input of ``height x width``.""" + shapes = [] + for block in self.blocks: + for layer in block: + height, width = layer.out_hw(height, width) + shapes.append((height, width, block[-1].out_channels)) + return shapes + + def __call__(self, x: FeatureMap) -> List[FeatureMap]: + """Run every block on ``x`` (kept); returns the block outputs (DRAM). Inner layer outputs are freed.""" + outs: List[FeatureMap] = [] + cur = x + for block in self.blocks: + for layer in block: + nxt = _to_dram(layer(cur)) + if cur is not x and all(cur is not o for o in outs): + free_maps(cur) + cur = nxt + outs.append(cur) + return outs + + def release(self) -> None: + for block in self.blocks: + for layer in block: + layer.release() + + def describe(self) -> List[List[Dict[str, Any]]]: + return [[layer.describe() for layer in block] for block in self.blocks] + + +class SecondFPN: + """SECONDFPN neck: ``deblocks[i]`` (a :class:`ConvSpec`, ReLU after) up-samples block output ``i``.""" + + def __init__(self, deblocks: Sequence[ConvSpec], *, policy: Optional[PrecisionPolicy] = None, + prefix: str = "neck"): + self.prefix = prefix + self.deblocks: List[Any] = [] + self.strides: List[int] = [] + for i, spec in enumerate(deblocks): + name = f"{prefix}.deblock{i}" + act = "relu" if spec.relu else None + prec = _precision(policy, name) + if spec.kind == "conv": + if spec.kernel != 1 or spec.stride != 1: + raise ValueError(f"{name}: a conv deblock must be 1x1 stride 1 (k={spec.kernel}, s={spec.stride})") + layer: Any = RowLinear(spec.weight, spec.bias, activation=act, precision=prec, + output_dtype=prec.activations, name=name) + self.strides.append(1) + elif spec.kind == "conv_transpose": + if spec.kernel != spec.stride: + raise ValueError(f"{name}: ConvTranspose deblocks need kernel == stride (k={spec.kernel}, " + f"s={spec.stride})") + if spec.stride == 1: + layer = RowLinear(np.asarray(spec.weight, np.float32)[:, :, 0, 0], spec.bias, activation=act, + precision=prec, output_dtype=prec.activations, name=name) + else: + layer = ConvTranspose2d(spec.weight, spec.bias, stride=spec.stride, activation=act, + precision=prec, output_dtype=prec.activations, name=name) + self.strides.append(spec.stride) + else: + raise ValueError(f"{name}: unknown kind {spec.kind!r}") + self.deblocks.append(layer) + + def __call__(self, blocks: Sequence[FeatureMap]) -> List[FeatureMap]: + """The deblock outputs (DRAM interleaved TILE maps of one grid); the inputs are kept.""" + if len(blocks) != len(self.deblocks): + raise ValueError(f"{self.prefix}: {len(blocks)} inputs for {len(self.deblocks)} deblocks") + outs = [] + for layer, x in zip(self.deblocks, blocks): + outs.append(_to_dram(layer(x))) + return outs + + def release(self) -> None: + for d in self.deblocks: + d.release() + + def describe(self) -> List[Dict[str, Any]]: + return [d.describe() for d in self.deblocks] + + +# ------------------------------------------------------------------------------------------- host oracles + +def _apply_torch(spec: ConvSpec, x): + """One layer in torch fp32 on an NCHW tensor.""" + import torch + import torch.nn.functional as F + + w = torch.from_numpy(np.ascontiguousarray(spec.weight, dtype=np.float32)) + b = None if spec.bias is None else torch.from_numpy(np.ascontiguousarray(spec.bias, dtype=np.float32)) + if spec.kind == "conv": + pad = spec.kernel // 2 if spec.padding is None else spec.padding + y = F.conv2d(x, w, b, stride=spec.stride, padding=pad) + else: + y = F.conv_transpose2d(x, w, b, stride=spec.stride) + return torch.relu(y) if spec.relu else y + + +def second_numpy(blocks: Sequence[Sequence[ConvSpec]], x_nchw: Any) -> List[np.ndarray]: + """fp32 oracle of :class:`Second` (torch): NCHW in, NCHW block outputs out.""" + import torch + + with torch.no_grad(): + x = torch.as_tensor(np.asarray(x_nchw, dtype=np.float32)) + outs = [] + for block in blocks: + for spec in block: + x = _apply_torch(spec, x) + outs.append(x.numpy().copy()) + return outs + + +def second_fpn_numpy(deblocks: Sequence[ConvSpec], blocks_nchw: Sequence[Any]) -> List[np.ndarray]: + """fp32 oracle of :class:`SecondFPN` (torch): NCHW in and out.""" + import torch + + with torch.no_grad(): + return [_apply_torch(s, torch.as_tensor(np.asarray(x, dtype=np.float32))).numpy().copy() + for s, x in zip(deblocks, blocks_nchw)] diff --git a/code/tt_depthpro2/ttaw/models/sparse_encoder.py b/code/tt_depthpro2/ttaw/models/sparse_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..8eb2e1b79bcbb14948bacfa8db5f0f309463b8e2 --- /dev/null +++ b/code/tt_depthpro2/ttaw/models/sparse_encoder.py @@ -0,0 +1,470 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C28: the gather-GEMM sparse-conv encoder on the device (PLAN.md 1.2 row C28; probe P4; host rulebooks: C13 +``ttaw.sparse``). Owned by the BEVFusion port; PTv3's sub-manifold stages are the second consumer. + +Every spconv layer of the Autoware graphs (sub-manifold and strided alike) is a gather (C13): ``y[o] = sum_k +W[:, k, :] @ x[nmap[o, k]] + b``. On the device one layer is: + +1. ONE ``ttnn.embedding`` (TILE + PADDED, P4) of the layer's tile-ordered im2col index (C13 ``im2col_index``, + uint32 ``[rows / 32, K * 32]``) into the bf16 ROW_MAJOR table ``[1, 1, V + 1, Cin_pad]`` of the layer's input rows + (the last row = the explicit zero sentinel ``V``, ``Cin_pad % 32 == 0``) -> ``[rows / 32, K * 32, Cin_pad]`` + whose tiles, in memory order, are the tiles of the im2col matrix ``[rows, K * Cin_pad]``; +2. ``ttnn.experimental.view`` to ``[1, 1, rows, K * Cin_pad]`` (metadata only); +3. a bias-free ``ttnn.matmul`` with the BN-folded im2col weight ``[K * Cin_pad, Cout_pad]`` into fp32 (C24 + ``RowMatmul``: no fused-bias epilogue rounds the fp32 accumulator), optionally a second one with the weight's + bf16 low term (``weight_terms=2``); +4. one exact fp32 ``ttnn.add`` of the bias (with the ReLU fused when there is no residual), or bias + the fp32 + identity of a basic block followed by the ReLU fused into the second add; +5. the next table: the fp32 output cast to bf16, untilized and given its zero row (C19 ``with_zero_rows``). + +**Activation terms.** ``ttnn.embedding`` is bf16-only, so a table rounds every layer's input to bf16 (8 significant +bits). A layer whose table is *two-term* (``in_terms=2``) carries ``hi = bf16(x)`` in channels ``[0, C)`` and ``lo = +bf16(x - hi)`` in ``[C, 2C)`` of the same table (~16 significant bits): the im2col weight repeats each tap's rows for +the ``lo`` block, so the same single gather and single matmul compute ``hi @ W + lo @ W``. Where ``2C <= 32`` (Cin 4 +of a VFE input, 16 at BEVFusion's level 1) the ``lo`` block rides in channels that the tile padding carries anyway: +free. A producer with ``out_terms=2`` writes its output columns twice (``[W | W]``) and splits them on the device into +``[hi | lo]`` (``y - bf16(y) * mask``, then one bf16 cast: exact). Consecutive layers must agree (the producer's +``out_terms`` is the consumer's ``in_terms``; :class:`SparseEncoder` checks it). + +Rows past a level's active count are computed (capacity padding: nothing data-dependent reaches the device) but +never gathered: every index points at an active row or at the sentinel, so no count is needed on the device. + +numpy only at import (ttnn / torch inside the device calls). Host oracle: :func:`sparse_encoder_numpy`, with the +device's bf16 table rounding modelled (``round_tables=True``). +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple + +import numpy as np + +from ..precision import Precision, PrecisionPolicy +from .second import free_maps + +__all__ = ["SparseConvSpec", "TtSparseConv", "SparseEncoder", "DEFAULT_PRECISION", "TILE_ROWS", "pad_channels", + "pack_table", "table_rows_numpy", "sparse_layer_numpy", "sparse_encoder_numpy", "dense_gather", + "im2col_weight"] + +TILE_ROWS = 32 +# fp32 weights (TF32-like products on this tree, P12), HiFi4, fp32 accumulation +DEFAULT_PRECISION = "HiFi4+fp32:w=fp32" + + +def pad_channels(c: int, multiple: int = TILE_ROWS) -> int: + """``c`` rounded up to a multiple of 32 (the table width a TILE embedding needs, P4).""" + return -(-int(c) // multiple) * multiple + + +def _bf16(a: np.ndarray) -> np.ndarray: + from ..tensors import round_to_bf16 + + return round_to_bf16(np.asarray(a, np.float32)) + + +@dataclass(frozen=True) +class SparseConvSpec: + """One BN-folded sparse conv: ``y = relu?(gather_conv(x, weight) + bias (+ identity))``. + + ``weight``: KRSC ``[Cout, k0, k1, k2, Cin]`` float32 (tap ``k = (a * k1 + b) * k2 + c``, C13 order) or already + ``[Cout, K, Cin]``; ``index``: the name of the gather index it reads (several layers may share one: the + sub-manifold convs of a level); ``residual``: the name of an earlier layer whose (fp32, pre-split) output is + added before the ReLU; ``in_terms`` / ``out_terms``: 1 (bf16 table) or 2 (``[hi | lo]`` table, module + docstring).""" + + name: str + weight: np.ndarray + bias: np.ndarray + index: str + residual: Optional[str] = None + relu: bool = True + in_terms: int = 1 + out_terms: int = 1 + + def __post_init__(self) -> None: + w = np.asarray(self.weight, np.float32) + if w.ndim not in (3, 5): + raise ValueError(f"{self.name}: weight must be KRSC [Cout, k0, k1, k2, Cin] or [Cout, K, Cin], got {w.shape}") + if np.shape(self.bias) != (w.shape[0],): + raise ValueError(f"{self.name}: bias must be ({w.shape[0]},), got {np.shape(self.bias)}") + if self.in_terms not in (1, 2) or self.out_terms not in (1, 2): + raise ValueError(f"{self.name}: terms must be 1 or 2") + if not (np.all(np.isfinite(w)) and np.all(np.isfinite(self.bias))): + raise ValueError(f"{self.name}: non-finite weights") + + @property + def weight3(self) -> np.ndarray: + w = np.asarray(self.weight, np.float32) + return w.reshape(w.shape[0], -1, w.shape[-1]) + + @property + def kernel_volume(self) -> int: + return int(self.weight3.shape[1]) + + @property + def in_channels(self) -> int: + return int(self.weight3.shape[2]) + + @property + def out_channels(self) -> int: + return int(self.weight3.shape[0]) + + @property + def cin_pad(self) -> int: + """Table width of the input: ``in_terms * Cin`` rounded up to 32.""" + return pad_channels(self.in_terms * self.in_channels) + + @property + def cout_pad(self) -> int: + """Output / next-table width: ``out_terms * Cout`` rounded up to 32.""" + return pad_channels(self.out_terms * self.out_channels) + + def matrix(self) -> np.ndarray: + """The im2col weight ``[K * cin_pad, cout_pad]`` float32 (:func:`im2col_weight`).""" + return im2col_weight(self.weight3, cin_pad=self.cin_pad, cout_pad=self.cout_pad, in_terms=self.in_terms, + out_terms=self.out_terms) + + def bias_row(self) -> np.ndarray: + """``(1, cout_pad)`` float32: the bias, repeated for the ``lo`` block when ``out_terms == 2``.""" + out = np.zeros((1, self.cout_pad), np.float32) + c = self.out_channels + for t in range(self.out_terms): + out[0, t * c:(t + 1) * c] = np.asarray(self.bias, np.float32) + return out + + def lo_mask(self) -> np.ndarray: + """``(1, cout_pad)`` float32: 1 on the ``lo`` output columns (``out_terms == 2``), else 0.""" + out = np.zeros((1, self.cout_pad), np.float32) + if self.out_terms == 2: + out[0, self.out_channels:2 * self.out_channels] = 1.0 + return out + + +def im2col_weight(weight3: np.ndarray, *, cin_pad: int, cout_pad: int, in_terms: int = 1, + out_terms: int = 1) -> np.ndarray: + """``[Cout, K, Cin]`` -> ``[K * cin_pad, cout_pad]``: row ``k * cin_pad + j`` = ``W[:, k, j mod Cin]`` for the + ``in_terms`` channel blocks (the ``lo`` block repeats the ``hi`` weights), zero for padding; columns repeated for + the ``out_terms`` blocks, zero padding beyond.""" + w = np.asarray(weight3, np.float32) + cout, K, cin = w.shape + if in_terms * cin > cin_pad or out_terms * cout > cout_pad: + raise ValueError(f"cin_pad {cin_pad} / cout_pad {cout_pad} too small for {in_terms} x {cin} / " + f"{out_terms} x {cout}") + m = np.zeros((K, cin_pad, cout_pad), np.float32) + wt = np.transpose(w, (1, 2, 0)) # (K, Cin, Cout) + for ti in range(in_terms): + for to in range(out_terms): + m[:, ti * cin:(ti + 1) * cin, to * cout:(to + 1) * cout] = wt + return m.reshape(K * cin_pad, cout_pad) + + +# --------------------------------------------------------------------------------------------- host tables + +def table_rows_numpy(x: np.ndarray, *, terms: int, width: int) -> np.ndarray: + """``(N, C)`` float rows -> ``(N, width)`` float32 table rows with the device's bf16 values: ``terms=1``: + ``bf16(x)`` in ``[0, C)``; ``terms=2``: ``hi = bf16(x)`` in ``[0, C)``, ``lo = bf16(x - hi)`` in ``[C, 2C)``; + zero elsewhere.""" + x = np.asarray(x, np.float32) + n, c = x.shape + if terms * c > width: + raise ValueError(f"{terms} x {c} channels do not fit a width of {width}") + out = np.zeros((n, width), np.float32) + hi = _bf16(x) + out[:, :c] = hi + if terms == 2: + out[:, c:2 * c] = _bf16(x - hi) + return out + + +def pack_table(x: np.ndarray, capacity: int, *, terms: int = 1, width: Optional[int] = None, + out: Optional[np.ndarray] = None) -> np.ndarray: + """The first layer's input table as a host array ``(1, 1, capacity + 1, width)`` float32 (bf16-exact values, + upload as bf16 ROW_MAJOR): the ``N <= capacity`` rows of ``x`` (:func:`table_rows_numpy`), zero rows after them, + and the zero sentinel row at ``capacity``. ``width`` defaults to ``terms * C`` rounded up to 32.""" + x = np.asarray(x, np.float32) + n, c = x.shape + if n > capacity: + raise ValueError(f"{n} rows exceed the capacity {capacity}") + width = pad_channels(terms * c) if width is None else int(width) + shape = (1, 1, int(capacity) + 1, width) + if out is None: + out = np.zeros(shape, np.float32) + elif out.shape != shape or out.dtype != np.float32: + raise ValueError(f"out must be float32 {shape}") + else: + out[...] = 0.0 + out[0, 0, :n] = table_rows_numpy(x, terms=terms, width=width) + return out + + +def sparse_layer_numpy(table: np.ndarray, nmap: np.ndarray, spec: SparseConvSpec, *, + identity: Optional[np.ndarray] = None) -> np.ndarray: + """Host oracle of one device layer on a host table ``(V + 1, cin_pad)`` (the last row the zero sentinel): + gathers by ``nmap`` (``-1`` -> sentinel), the im2col matmul in float64, bias, identity, ReLU -> ``(N, Cout)`` + float32 (the logical columns).""" + t = np.asarray(table, np.float64).reshape(-1, spec.cin_pad) + sentinel = t.shape[0] - 1 + idx = np.where(np.asarray(nmap) >= 0, nmap, sentinel).astype(np.int64) + cols = t[idx].reshape(idx.shape[0], -1) # (N, K * cin_pad) + m = spec.matrix().astype(np.float64)[:, :spec.out_channels] + y = cols @ m + np.asarray(spec.bias, np.float64) + if identity is not None: + y = y + np.asarray(identity, np.float64) + if spec.relu: + y = np.maximum(y, 0.0) + return y.astype(np.float32) + + +def sparse_encoder_numpy(specs: Sequence[SparseConvSpec], features: np.ndarray, maps: Mapping[str, np.ndarray], *, + round_tables: bool = True) -> Dict[str, np.ndarray]: + """Host oracle of :class:`SparseEncoder`: ``features`` ``(N0, C0)`` (the first layer's input rows) and the + neighbour maps by index name -> ``{layer name: (N, Cout) float32}``. ``round_tables=True`` models the device's + tables (bf16 or two-term ``hi + lo``, per the specs' terms); False is the fp32 network (the reference).""" + outs: Dict[str, np.ndarray] = {} + x = np.asarray(features, np.float32) + for spec in specs: + if round_tables: + table = table_rows_numpy(x, terms=spec.in_terms, width=spec.cin_pad) + else: + table = np.zeros((x.shape[0], spec.cin_pad), np.float32) # an exact table: the lo block is zero + table[:, :x.shape[1]] = x + table = np.concatenate([table, np.zeros((1, spec.cin_pad), np.float32)], 0) + ident = outs[spec.residual] if spec.residual else None + y = sparse_layer_numpy(table, maps[spec.index], spec, identity=ident) + outs[spec.name] = y + x = y + return outs + + +# --------------------------------------------------------------------------------------------- device layer + +class TtSparseConv: + """One device layer of :class:`SparseConvSpec` (module docstring, steps 1-4). ``weight_terms=2`` runs the + im2col weight as two bf16 terms (two matmuls, ~16 significant bits) instead of fp32 weights (TF32-like + products, P12). Device weights are uploaded by the first call (outside any capture).""" + + def __init__(self, spec: SparseConvSpec, *, precision: Any = DEFAULT_PRECISION, weight_terms: int = 1): + from .pillars import RowMatmul + + self.spec = spec + self.name = spec.name + self.precision = Precision.parse(precision) if not isinstance(precision, Precision) else precision + self.weight_terms = int(weight_terms) + if self.weight_terms not in (1, 2): + raise ValueError(f"{self.name}: weight_terms must be 1 or 2") + m = spec.matrix() + if self.weight_terms == 2: + if self.precision.weights != "bfloat16": + self.precision = self.precision.with_(weights="bfloat16") + hi = _bf16(m) + self.mm = [RowMatmul(hi, precision=self.precision, name=f"{self.name}.whi"), + RowMatmul(_bf16(m - hi), precision=self.precision, name=f"{self.name}.wlo")] + else: + self.mm = [RowMatmul(m, precision=self.precision, name=self.name)] + self.k_in = int(m.shape[0]) + self._consts: Optional[Tuple[Any, Any]] = None + + @property + def rows_per_block(self) -> int: + return TILE_ROWS + + def _const(self, device: Any) -> Tuple[Any, Any]: + import torch + import ttnn + + if self._consts is None: + def up(a): + return ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(a, np.float32)), dtype=ttnn.float32, + layout=ttnn.TILE_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) + + mask = up(self.spec.lo_mask()) if self.spec.out_terms == 2 else None + self._consts = (up(self.spec.bias_row()), mask) + return self._consts + + def gather(self, table: Any, index: Any): + """The im2col operand ``[1, 1, rows, K * cin_pad]`` bf16 TILE (one PADDED embedding + a view).""" + import ttnn + + width = int(table.shape[-1]) + if width != self.spec.cin_pad: + raise ValueError(f"{self.name}: table width {width} != cin_pad {self.spec.cin_pad}") + k = self.spec.kernel_volume + if int(index.shape[-1]) != k * TILE_ROWS: + raise ValueError(f"{self.name}: index has {int(index.shape[-1])} columns, expected {k * TILE_ROWS}") + rows = int(index.shape[0]) * TILE_ROWS + sentinel = int(table.shape[-2]) - 1 + g = ttnn.embedding(index, table, layout=ttnn.TILE_LAYOUT, padding_idx=sentinel, + embeddings_type=ttnn.EmbeddingsType.PADDED) # [rows / 32, K * 32, cin_pad] + return ttnn.experimental.view(g, [1, 1, rows, k * width]) + + def __call__(self, table: Any, index: Any, identity: Any = None): + """``table`` bf16 ROW_MAJOR ``[1, 1, V + 1, cin_pad]`` (row V zero), ``index`` uint32 ``[rows / 32, K * 32]``, + ``identity`` an fp32 TILE ``[1, 1, rows, cout_pad]`` (the residual source's output) or None -> the fp32 TILE + output ``[1, 1, rows, cout_pad]`` (DRAM). The inputs are kept.""" + import ttnn + + from ..ops.conv import unary_with_param + + x = self.gather(table, index) + ys = [mm(x) for mm in self.mm] + free_maps(x) + y = ys[-1] + for extra in reversed(ys[:-1]): # the small term first, then the main one + s = ttnn.add(extra, y, memory_config=ttnn.DRAM_MEMORY_CONFIG) + free_maps(extra, y) + y = s + bias, _ = self._const(table.device()) + relu = [unary_with_param("relu")] if self.spec.relu else [] + if identity is None: + out = ttnn.add(y, bias, activations=relu, memory_config=ttnn.DRAM_MEMORY_CONFIG) + free_maps(y) + return out + s = ttnn.add(y, bias, memory_config=ttnn.DRAM_MEMORY_CONFIG) + free_maps(y) + out = ttnn.add(s, identity, activations=relu, memory_config=ttnn.DRAM_MEMORY_CONFIG) + free_maps(s) + return out + + def to_table(self, y: Any): + """The fp32 output -> the next layer's bf16 ROW_MAJOR table ``[1, 1, rows + 1, cout_pad]`` (zero last row; + ``[hi | lo]`` split for ``out_terms == 2``). ``y`` is kept.""" + import ttnn + + from ..ops.gather import with_zero_rows + + if self.spec.out_terms == 2: + _, mask = self._const(y.device()) + hi = ttnn.typecast(y, ttnn.bfloat16) + h32 = ttnn.typecast(hi, ttnn.float32) + free_maps(hi) + hm = ttnn.multiply(h32, mask) + free_maps(h32) + r = ttnn.subtract(y, hm) + free_maps(hm) + t = ttnn.typecast(r, ttnn.bfloat16) + free_maps(r) + else: + t = ttnn.typecast(y, ttnn.bfloat16) + table = with_zero_rows(t, 1) + free_maps(t) + return table + + def release(self) -> None: + for mm in self.mm: + mm.release() + if self._consts is not None: + free_maps(*[c for c in self._consts if c is not None]) + self._consts = None + + def describe(self) -> Dict[str, Any]: + s = self.spec + return {"name": s.name, "index": s.index, "cin": s.in_channels, "cout": s.out_channels, "K": s.kernel_volume, + "cin_pad": s.cin_pad, "cout_pad": s.cout_pad, "in_terms": s.in_terms, "out_terms": s.out_terms, + "residual": s.residual, "relu": s.relu, "weight_terms": self.weight_terms, + "precision": self.precision.label} + + +class SparseEncoder: + """A chain of :class:`TtSparseConv` layers (in order; each reads the previous layer's table, the first one the + given input table). ``policy`` resolves ```` to a precision (default + :data:`DEFAULT_PRECISION`); ``weight_terms`` 1 or 2 for every layer (or a ``{name: terms}`` mapping).""" + + def __init__(self, specs: Sequence[SparseConvSpec], *, policy: Optional[PrecisionPolicy] = None, + weight_terms: Any = 1, name: str = "sparse"): + if not specs: + raise ValueError("no layers") + self.name = name + names = [s.name for s in specs] + if len(set(names)) != len(names): + raise ValueError("layer names must be unique") + for prev, cur in zip(specs[:-1], specs[1:]): + if prev.out_terms != cur.in_terms or prev.cout_pad != cur.cin_pad: + raise ValueError(f"{cur.name}: input terms / width {cur.in_terms} / {cur.cin_pad} != the output of " + f"{prev.name} ({prev.out_terms} / {prev.cout_pad})") + if prev.out_channels != cur.in_channels: + raise ValueError(f"{cur.name}: {cur.in_channels} input channels after {prev.out_channels}") + seen = set() + for s in specs: + if s.residual is not None: + if s.residual not in seen: + raise ValueError(f"{s.name}: residual {s.residual!r} is not an earlier layer") + src = next(p for p in specs if p.name == s.residual) + if src.cout_pad != s.cout_pad or src.out_channels != s.out_channels or src.out_terms != s.out_terms: + raise ValueError(f"{s.name}: residual {s.residual!r} has another output layout") + seen.add(s.name) + self.specs = list(specs) + self.layers: List[TtSparseConv] = [] + for s in specs: + prec = policy.resolve(s.name) if policy is not None else Precision.parse(DEFAULT_PRECISION) + wt = int(weight_terms.get(s.name, 1)) if isinstance(weight_terms, Mapping) else int(weight_terms) + self.layers.append(TtSparseConv(s, precision=prec, weight_terms=wt)) + # the last use of every layer output (as a residual identity), to free it as early as possible + self._last_use: Dict[str, int] = {} + for i, s in enumerate(specs): + if s.residual is not None: + self._last_use[s.residual] = i + + @property + def index_names(self) -> List[str]: + """The gather indices the chain reads, in first-use order.""" + out: List[str] = [] + for s in self.specs: + if s.index not in out: + out.append(s.index) + return out + + @property + def input_width(self) -> int: + return self.specs[0].cin_pad + + @property + def input_terms(self) -> int: + return self.specs[0].in_terms + + def __call__(self, table: Any, indices: Mapping[str, Any], taps: Optional[Dict[str, Any]] = None, + keep_table: bool = True): + """``table``: the first layer's bf16 ROW_MAJOR input table (kept); ``indices``: ``{index name: uint32 device + tensor}``; ``taps`` (a dict) collects every layer's fp32 output ``[1, 1, rows, cout_pad]`` by layer name. + Returns ``(y, out_table)``: the last layer's fp32 output and (``keep_table``) its bf16 ROW_MAJOR table + (zero sentinel row appended), else ``(y, None)``.""" + missing = [n for n in self.index_names if n not in indices] + if missing: + raise KeyError(f"{self.name}: missing gather indices {missing}") + cur_table = table + outs: Dict[str, Any] = {} + y = None + n = len(self.layers) + for i, (layer, spec) in enumerate(zip(self.layers, self.specs)): + ident = outs[spec.residual] if spec.residual else None + y = layer(cur_table, indices[spec.index], ident) + if cur_table is not table: + free_maps(cur_table) + # free outputs whose last residual use was this layer (unless tapped) + for name, last in list(self._last_use.items()): + if last == i and name in outs and (taps is None): + free_maps(outs.pop(name)) + outs[spec.name] = y + if taps is not None: + taps[spec.name] = y + last_layer = i == n - 1 + if not last_layer or keep_table: + cur_table = layer.to_table(y) + if not last_layer and taps is None and spec.name not in self._last_use: + free_maps(outs.pop(spec.name)) + return y, (cur_table if keep_table else None) + + def release(self) -> None: + for layer in self.layers: + layer.release() + + def describe(self) -> Dict[str, Any]: + return {"name": self.name, "layers": [layer.describe() for layer in self.layers], + "indices": self.index_names} + + +def dense_gather(table: Any, index: Any): + """To-dense as a gather (C13 ``dense_gather_index``, one slice): ``table`` bf16 ROW_MAJOR ``[1, 1, V + 1, C]`` + (row V zero), ``index`` uint32 ``[1, cells]`` -> ``[1, 1, cells, C]`` bf16 TILE (empty cells exactly 0).""" + from ..ops.gather import gather_rows + + return gather_rows(index, table, sentinel=int(table.shape[-2]) - 1) diff --git a/code/tt_depthpro2/ttaw/models/transfusion_head.py b/code/tt_depthpro2/ttaw/models/transfusion_head.py new file mode 100644 index 0000000000000000000000000000000000000000..cc4c5793cfcf5c843afb33daeb5ecf19c67896e8 --- /dev/null +++ b/code/tt_depthpro2/ttaw/models/transfusion_head.py @@ -0,0 +1,584 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C26: the TransFusion query head on the device (PLAN.md section 1.2 row C26; TransFusion builds it, BEVFusion and +PTv3 reuse it; probes P4, P7, P8, P13). + +The dense part of a TransFusion head (shared conv, heatmap convs) is C17 / C24 work; this module is what follows the +local-max heatmap (C22): query selection (C21), query initialisation, ONE post-norm decoder layer and the prediction +heads, as one traceable device graph with one packed output. The model-agnostic weights record +:class:`QueryHeadWeights` (host numpy, BN folded) describes it: + +- ``class_table`` ``(C, d)``: the class encoding (``Conv1d(one_hot(c))`` = ``W[:, c] + b``, an exact row gather); +- ``bev_pos`` ``(cells, 2)``: the model's constant BEV position of every feature cell (TF / PT ``(x + 0.5, y + 0.5)`` + with ``k = y * W + x``; BF ``(i + 0.5, j + 0.5)`` with ``k = i * 180 + j``); a query's position is ``bev_pos[pos]``; +- ``self_posembed`` / ``cross_posembed``: the position MLPs ``Conv1d 2 -> d + ReLU, Conv1d d -> d`` (BN folded); +- the decoder layer: self-attention on ``s = x + pe(query_pos)`` (Q = K = V = s), add + LayerNorm, cross-attention + of ``x + pe(query_pos)`` over ``key = lidar_feat + pe_k(bev_pos)`` (K = V = key), add + LN, FFN (ReLU), add + LN; +- the prediction heads ``(name, Conv1d d -> h + ReLU, Conv1d h -> c)``. + +Device form (every rewrite exact in real arithmetic; the oracle :class:`QueryHeadOracle` runs the literal forms): + +| step | device ops | +|---|---| +| selection | C21 ``TopKSelect``: class-major bf16 row of the local-max heatmap, ``topk_large_indices`` k = ``padded_k(K)``, exact fp32 decode -> uint32 ``pos`` / ``cls`` rows (or given indices: teacher forcing) | +| query init | ``ttnn.embedding`` of the ``lidar_feat`` rows (bf16) by ``pos`` + the class-table row by ``cls``; the query position embedding is a function of ``pos`` only, so it is a constant **QPE table** ``self_posembed(bev_pos)`` (host float64 -> bf16) gathered by ``pos``: ``query_pos`` itself never passes through bf16 (S:transfusion:241) | +| keys | ``key = lidar_feat + KPE`` with the constant ``KPE = cross_posembed(bev_pos)`` table (the 0.6 GMAC position branch leaves the per-frame graph, S:transfusion:279) | +| attention | C20 ``sdpa`` (``is_causal=False``, ``scale`` from the weights, chunk table), the head dim zero-padded to 32 in the projection weights (``pad_head_columns`` / ``pad_head_rows``, exact); self-attention on the logical ``K`` queries with no mask, Q / K / V from one fused projection; cross-attention over every cell | +| LayerNorm | ``ttnn.layer_norm(o, residual_input_tensor=x, epsilon=)`` (never ttnn's 1e-12 default) | +| heads | merged: ``relu(x @ [Wh_1 ... Wh_n] + bh)`` then the block-diagonal ``@ Wo + bo`` (padded to 32), fp32 out | +| query heat | ``ttnn.embedding`` of the local-max heatmap rows (classes zero-padded to 32) by ``pos``: every class at the query's cell (the TF / mmdeploy score ``query_heat * sigmoid(heatmap)``; BF / PT one-hot it on the host) | + +Output (``__call__``): ``{"heads": fp32 [1, 1, K, 32], "query_heat": bf16 [1, 1, Kp, 32], "indices": fp32 [1, 1, 1, +Kp]}`` (``Kp = padded_k(K)``; the first ``K`` indices are the proposals, fp32 holds them exactly), ready for +``ttaw.trace.pack_outputs``. :func:`assemble_transfusion` turns the read-back arrays into the TF / mmdeploy graph +outputs ``cls_score0``, ``bbox_pred0``, ``dir_cls_pred0`` (``center + query_pos`` in float32 on the host). + +Limits: one decoder layer (the TF, BF and PT heads have one; a second layer would re-embed the predicted centres, +which no constant table can do); ``bev_pos`` must be finite. Precision (``ttaw.precision`` policy, module names +``.self_attn``, ``.cross_attn``, ``.ffn``, ``.heads``, ``.norm``): fp32 weights, HiFi4 + fp32 accumulation, +bf16 activations (SDPA takes bf16); the tables are bf16 (their rows are model activations, rounded once). + +numpy only at import; ttnn / torch are imported inside the functions that need them. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Dict, Optional, Tuple + +import numpy as np + +from ..ops.attention import pad_head_columns, pad_head_rows, padded_head_dim +from ..ops.topk import TopKSelect, padded_k +from ..precision import Precision, PrecisionPolicy +from .second import RowLinear, free_maps + +__all__ = ["MHAWeights", "PosEmbedMLP", "PredictionHead", "QueryHeadWeights", "TransFusionQueryHead", + "QueryHeadOracle", "assemble_transfusion", "DEFAULT_PRECISION", "default_policy", "HEAD_PAD"] + +HEAD_PAD = 32 +DEFAULT_PRECISION = "HiFi4+fp32:w=fp32" + + +def default_policy() -> PrecisionPolicy: + """fp32 weights, HiFi4 + fp32 accumulation, bf16 activations for every module of the head.""" + return PrecisionPolicy(default=DEFAULT_PRECISION) + + +def _f32(a: Any) -> np.ndarray: + """A writable float32 copy (ONNX-derived arrays may be read-only; torch warns about those).""" + return np.array(a, dtype=np.float32, copy=True, order="C") + + +# ------------------------------------------------------------------------------------------------- weights + +@dataclass(frozen=True) +class MHAWeights: + """``nn.MultiheadAttention`` as exported, ``[in, out]`` layout: ``q = x_q @ wq + bq`` (likewise k / v), per head + ``softmax(scale * q k^T) v``, ``out = concat_heads @ wo + bo``.""" + + wq: np.ndarray + bq: np.ndarray + wk: np.ndarray + bk: np.ndarray + wv: np.ndarray + bv: np.ndarray + wo: np.ndarray + bo: np.ndarray + num_heads: int + scale: float + + @property + def head_dim(self) -> int: + return int(np.shape(self.wq)[1]) // int(self.num_heads) + + @property + def dim(self) -> int: + return int(np.shape(self.wq)[0]) + + +@dataclass(frozen=True) +class PosEmbedMLP: + """``Conv1d 2 -> d`` (BN folded) + ReLU, ``Conv1d d -> d``; ``[in, out]`` weights.""" + + w0: np.ndarray + b0: np.ndarray + w1: np.ndarray + b1: np.ndarray + + def numpy(self, pos: Any) -> np.ndarray: + """``(P, 2)`` positions -> ``(P, d)`` float64.""" + p = np.asarray(pos, np.float64) + h = np.maximum(p @ np.asarray(self.w0, np.float64) + np.asarray(self.b0, np.float64), 0.0) + return h @ np.asarray(self.w1, np.float64) + np.asarray(self.b1, np.float64) + + +@dataclass(frozen=True) +class PredictionHead: + """``Conv1d d -> h`` + ReLU, ``Conv1d h -> c`` (``[in, out]`` weights).""" + + name: str + w_hidden: np.ndarray + b_hidden: np.ndarray + w_out: np.ndarray + b_out: np.ndarray + + @property + def channels(self) -> int: + return int(np.shape(self.w_out)[1]) + + +@dataclass(frozen=True) +class QueryHeadWeights: + """Everything the query head needs, model-agnostic (module docstring). ``height`` / ``width``: the feature grid + (``cells = height * width`` keys, row-major ``k = y * width + x`` as the dense maps are laid out).""" + + height: int + width: int + num_classes: int + num_proposals: int + class_table: np.ndarray # (C, d) + bev_pos: np.ndarray # (cells, 2) + self_posembed: PosEmbedMLP + cross_posembed: PosEmbedMLP + self_attn: MHAWeights + cross_attn: MHAWeights + norms: Tuple[Tuple[np.ndarray, np.ndarray, float], ...] # (gamma, beta, eps) x 3: after self, cross, FFN + ffn: Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] # w1 (d, f), b1, w2 (f, d), b2 + heads: Tuple[PredictionHead, ...] + + @property + def cells(self) -> int: + return int(self.height) * int(self.width) + + @property + def dim(self) -> int: + return int(np.shape(self.class_table)[1]) + + def validate(self) -> None: + d, c, cells = self.dim, int(self.num_classes), self.cells + if np.shape(self.class_table) != (c, d): + raise ValueError(f"class_table {np.shape(self.class_table)} != ({c}, {d})") + if np.shape(self.bev_pos) != (cells, 2) or not np.all(np.isfinite(self.bev_pos)): + raise ValueError(f"bev_pos must be finite ({cells}, 2), got {np.shape(self.bev_pos)}") + for a in (self.self_attn, self.cross_attn): + if a.dim != d or np.shape(a.wo) != (a.num_heads * a.head_dim, d): + raise ValueError("attention weights do not match the model width") + if not (np.isfinite(a.scale) and a.scale > 0): + raise ValueError(f"attention scale {a.scale}") + if len(self.norms) != 3: + raise ValueError("a decoder layer has three LayerNorms") + if np.shape(self.ffn[0])[0] != d or np.shape(self.ffn[2])[1] != d: + raise ValueError("FFN weights do not match the model width") + if not self.heads or any(np.shape(h.w_hidden)[0] != d for h in self.heads): + raise ValueError("prediction heads do not read the model width") + if sum(h.channels for h in self.heads) > HEAD_PAD: + raise ValueError(f"the merged head output is padded to {HEAD_PAD} channels") + if c > HEAD_PAD: + raise ValueError(f"the query heat rows hold at most {HEAD_PAD} classes") + padded_k(self.num_proposals) + if self.num_proposals > cells * c: + raise ValueError("more proposals than heatmap entries") + + # ---- host tables (float64, rounded once by the device upload) ------------------------------------------ + def query_pos_table(self) -> np.ndarray: + """``self_posembed(bev_pos)`` ``(cells, d)``: the query position embedding of every cell.""" + return self.self_posembed.numpy(self.bev_pos) + + def key_pos_table(self) -> np.ndarray: + """``cross_posembed(bev_pos)`` ``(cells, d)``: the input-independent key position embedding.""" + return self.cross_posembed.numpy(self.bev_pos) + + def merged_heads(self, pad_to: int = HEAD_PAD): + """``(Wh, bh, Wo, bo, slices)``: ``relu(x @ Wh + bh) @ Wo + bo`` with the block-diagonal ``Wo`` padded to + ``pad_to`` columns; ``slices`` = ``[(name, start, stop)]`` of each head's output channels (exact rewrite).""" + wh = np.concatenate([_f32(h.w_hidden) for h in self.heads], axis=1) + bh = np.concatenate([_f32(h.b_hidden) for h in self.heads]) + rows = wh.shape[1] + cols = sum(h.channels for h in self.heads) + width = max(pad_to, -(-cols // pad_to) * pad_to) + wo = np.zeros((rows, width), np.float32) + bo = np.zeros(width, np.float32) + slices, r, c = [], 0, 0 + for h in self.heads: + hr, hc = np.shape(h.w_hidden)[1], h.channels + wo[r:r + hr, c:c + hc] = _f32(h.w_out) + bo[c:c + hc] = _f32(h.b_out) + slices.append((h.name, c, c + hc)) + r, c = r + hr, c + hc + return wh, bh, wo, bo, slices + + +# ---------------------------------------------------------------------------------------------- device + +class _LayerNorm: + def __init__(self, gamma: Any, beta: Any, eps: float, precision: Precision, name: str): + self.gamma, self.beta, self.eps = _f32(gamma).reshape(1, -1).copy(), _f32(beta).reshape(1, -1).copy(), float(eps) + self.precision = precision + self.name = name + self._dev: Optional[Tuple[Any, Any, Any]] = None + + def upload(self, device: Any): + import torch + import ttnn + + def up(a): + return ttnn.from_torch(torch.from_numpy(a), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, device=device, + memory_config=ttnn.DRAM_MEMORY_CONFIG) + + self._dev = (up(self.gamma), up(self.beta), self.precision.compute_kernel_config()) + return self._dev + + def __call__(self, x: Any, residual: Any): + """``LayerNorm(x + residual)`` (one ``ttnn.layer_norm`` with a fused residual add).""" + import ttnn + + g, b, cfg = self._dev or self.upload(x.device()) + return ttnn.layer_norm(x, residual_input_tensor=residual, weight=g, bias=b, epsilon=self.eps, + compute_kernel_config=cfg, memory_config=ttnn.DRAM_MEMORY_CONFIG) + + def release(self) -> None: + if self._dev is not None: + free_maps(self._dev[0], self._dev[1]) + self._dev = None + + +class TransFusionQueryHead: + """The query head of :class:`QueryHeadWeights` on the device (module docstring). Device weights and tables are + uploaded by :meth:`prepare` (or the first call), outside any capture; the forward is traceable.""" + + def __init__(self, weights: QueryHeadWeights, *, policy: Optional[PrecisionPolicy] = None, prefix: str = "head", + attn_fp32_acc: bool = False, name: str = "query_head"): + weights.validate() + self.weights = weights + self.prefix = prefix + self.name = name + self.policy = policy or default_policy() + self.attn_fp32_acc = bool(attn_fp32_acc) + self.dim = weights.dim + self.cells = weights.cells + self.classes = int(weights.num_classes) + self.k = int(weights.num_proposals) + self.select = TopKSelect(self.cells, self.classes, self.k, name=f"{prefix}.topk") + self.kp = self.select.kp + sa, ca = weights.self_attn, weights.cross_attn + self.heads_self, self.hd_self = int(sa.num_heads), sa.head_dim + self.heads_cross, self.hd_cross = int(ca.num_heads), ca.head_dim + self.scale_self, self.scale_cross = float(sa.scale), float(ca.scale) + + def prec(module: str) -> Precision: + return self.policy.resolve(f"{prefix}.{module}") + + def cols(w, b, a: MHAWeights): + return pad_head_columns(_f32(w), _f32(b), a.num_heads, a.head_dim) + + p_sa, p_ca, p_ffn, p_heads = prec("self_attn"), prec("cross_attn"), prec("ffn"), prec("heads") + q, bq = cols(sa.wq, sa.bq, sa) + k, bk = cols(sa.wk, sa.bk, sa) + v, bv = cols(sa.wv, sa.bv, sa) + self.self_qkv = RowLinear(np.concatenate([q, k, v], axis=1), np.concatenate([bq, bk, bv]), precision=p_sa, + name=f"{prefix}.self_attn.qkv") + self.self_out = RowLinear(pad_head_rows(_f32(sa.wo), sa.num_heads, sa.head_dim), _f32(sa.bo), + precision=p_sa, name=f"{prefix}.self_attn.out") + self.cross_q = RowLinear(*cols(ca.wq, ca.bq, ca), precision=p_ca, name=f"{prefix}.cross_attn.q") + self.cross_k = RowLinear(*cols(ca.wk, ca.bk, ca), precision=p_ca, name=f"{prefix}.cross_attn.k") + self.cross_v = RowLinear(*cols(ca.wv, ca.bv, ca), precision=p_ca, name=f"{prefix}.cross_attn.v") + self.cross_out = RowLinear(pad_head_rows(_f32(ca.wo), ca.num_heads, ca.head_dim), _f32(ca.bo), + precision=p_ca, name=f"{prefix}.cross_attn.out") + w1, b1, w2, b2 = weights.ffn + self.ffn1 = RowLinear(_f32(w1), _f32(b1), activation="relu", precision=p_ffn, name=f"{prefix}.ffn.0") + self.ffn2 = RowLinear(_f32(w2), _f32(b2), precision=p_ffn, name=f"{prefix}.ffn.1") + wh, bh, wo, bo, self.head_slices = weights.merged_heads() + self.heads_hidden = RowLinear(wh, bh, activation="relu", precision=p_heads, name=f"{prefix}.heads.hidden") + self.heads_out = RowLinear(wo, bo, precision=p_heads, output_dtype="float32", name=f"{prefix}.heads.out") + p_norm = prec("norm") + self.norms = [_LayerNorm(g, b, eps, p_norm, f"{prefix}.norm{i}") for i, (g, b, eps) in enumerate(weights.norms)] + self._tables: Optional[Dict[str, Any]] = None + + # ---- device constants -------------------------------------------------------------------------------- + def prepare(self, device: Any) -> None: + """Upload the tables (bf16: class table and QPE as ROW_MAJOR gather tables, KPE as a TILE map) and the + LayerNorm rows. The linears upload their weights on their first call (the warm-up).""" + import torch + import ttnn + + if self._tables is not None: + return + w = self.weights + + def up(a: np.ndarray, layout): + t = torch.from_numpy(_f32(a).reshape(1, 1, a.shape[0], a.shape[1])) + return ttnn.from_torch(t, dtype=ttnn.bfloat16, layout=layout, device=device, + memory_config=ttnn.DRAM_MEMORY_CONFIG) + + self._tables = {"class": up(_f32(w.class_table), ttnn.ROW_MAJOR_LAYOUT), + "qpe": up(w.query_pos_table(), ttnn.ROW_MAJOR_LAYOUT), + "kpe": up(w.key_pos_table(), ttnn.TILE_LAYOUT)} + for n in self.norms: + n.upload(device) + + def _t(self, device: Any) -> Dict[str, Any]: + if self._tables is None: + self.prepare(device) + return self._tables # type: ignore[return-value] + + # ---- forward pieces ------------------------------------------------------------------------------------ + @staticmethod + def _rows(t: Any, n: int): + """``[1, n, D]`` / ``[1, 1, n, D]`` -> ``[1, 1, n, D]`` (a view).""" + import ttnn + + return ttnn.reshape(t, (1, 1, int(n), int(t.shape[-1]))) + + def _gather(self, index: Any, table: Any): + import ttnn + + return self._rows(ttnn.embedding(index, table, layout=ttnn.TILE_LAYOUT), int(index.shape[-1])) + + def init_queries(self, lidar_feat: Any, pos: Any, cls: Any) -> Tuple[Any, Any]: + """``lidar_feat`` TILE ``[1, 1, cells, d]``, ``pos`` / ``cls`` uint32 ROW_MAJOR ``[1, Kp]`` -> ``(x, qpe)`` + TILE ``[1, 1, K, d]``: the initial queries ``lidar_feat[pos] + class_table[cls]`` and their position + embeddings ``QPE[pos]``.""" + import ttnn + + t = self._t(lidar_feat.device()) + table = ttnn.to_layout(lidar_feat, ttnn.ROW_MAJOR_LAYOUT) + feat = self._gather(pos, table) + free_maps(table) + cemb = self._gather(cls, t["class"]) + x_p = ttnn.add(feat, cemb) + free_maps(feat, cemb) + qpe_p = self._gather(pos, t["qpe"]) + if self.kp == self.k: + return x_p, qpe_p + x = ttnn.slice(x_p, [0, 0, 0, 0], [1, 1, self.k, self.dim]) + qpe = ttnn.slice(qpe_p, [0, 0, 0, 0], [1, 1, self.k, self.dim]) + free_maps(x_p, qpe_p) + return x, qpe + + def keys(self, lidar_feat: Any): + """``lidar_feat + KPE`` (TILE ``[1, 1, cells, d]``): the cross-attention key / value input.""" + import ttnn + + return ttnn.add(lidar_feat, self._t(lidar_feat.device())["kpe"]) + + def _sdpa(self, q, k, v, scale: float): + from ..ops.attention import sdpa + + return sdpa(q, k, v, scale=scale, fp32_acc=self.attn_fp32_acc, concat_heads=True) + + def decoder(self, x: Any, qpe: Any, key: Any, taps: Optional[Dict[str, Any]] = None): + """One post-norm decoder layer on ``x`` ``[1, 1, K, d]`` -> ``[1, 1, K, d]`` (``key``: :meth:`keys`).""" + import ttnn + + from ..ops.attention import split_heads, split_qkv + + s = ttnn.add(x, qpe) + qkv = self.self_qkv(s) + free_maps(s) + q, k, v = split_qkv(qkv, self.heads_self) + free_maps(qkv) + a = self._sdpa(q, k, v, self.scale_self) + free_maps(q, k, v) + o = self.self_out(a) + free_maps(a) + x1 = self.norms[0](o, x) + free_maps(o) + if taps is not None: + taps["decoder.self_attn"] = x1 + qc_in = ttnn.add(x1, qpe) + qc = self.cross_q(qc_in) + free_maps(qc_in) + kc, vc = self.cross_k(key), self.cross_v(key) + qh, kh, vh = (split_heads(t, self.heads_cross) for t in (qc, kc, vc)) + free_maps(qc, kc, vc) + a = self._sdpa(qh, kh, vh, self.scale_cross) + free_maps(qh, kh, vh) + o = self.cross_out(a) + free_maps(a) + x2 = self.norms[1](o, x1) + free_maps(o) + if taps is not None: + taps["decoder.cross_attn"] = x2 + else: + free_maps(x1) + h = self.ffn1(x2) + f = self.ffn2(h) + free_maps(h) + x3 = self.norms[2](f, x2) + free_maps(f) + if taps is None: + free_maps(x2) + return x3 + + def predict(self, x: Any): + """The merged prediction heads: ``[1, 1, K, d]`` -> fp32 ``[1, 1, K, 32]`` (``head_slices`` channels).""" + hid = self.heads_hidden(x) + out = self.heads_out(hid) + free_maps(hid) + return out + + def query_heat(self, heat_nms: Any, pos: Any): + """The local-max heatmap rows (every class, zero-padded to 32) at the proposals' cells: bf16 TILE + ``[1, 1, Kp, 32]``.""" + import ttnn + + padded = ttnn.pad(heat_nms, [(0, 0), (0, 0), (0, 0), (0, HEAD_PAD - self.classes)], 0.0) + table = ttnn.to_layout(padded, ttnn.ROW_MAJOR_LAYOUT) + free_maps(padded) + out = self._gather(pos, table) + free_maps(table) + return out + + def _indices_tile(self, indices: Any): + """uint32 ROW_MAJOR ``[1, Kp]`` -> fp32 ``[1, 1, 1, Kp]`` ROW_MAJOR-ready tensor (exact below 2**24).""" + import ttnn + + t = ttnn.to_layout(indices, ttnn.TILE_LAYOUT) + f = ttnn.typecast(t, ttnn.float32) + free_maps(t) + return ttnn.reshape(f, (1, 1, 1, int(indices.shape[-1]))) + + def __call__(self, lidar_feat: Any, heat_nms: Any, indices: Optional[Any] = None, + taps: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + """``lidar_feat`` TILE ``[1, 1, cells, d]`` (bf16), ``heat_nms`` TILE ``[1, 1, cells, C]`` bf16 (C22's + output), ``indices``: None (device top-k) or a uint32 ROW_MAJOR ``[1, Kp]`` input (teacher forcing). Returns + ``{"heads", "query_heat", "indices"}`` (module docstring); ``taps`` (a dict) also collects ``query.feat``, + ``decoder.query_pos_embed``, ``decoder.self_attn``, ``decoder.cross_attn``, ``decoder.out``.""" + idx = self.select.indices(heat_nms) if indices is None else indices + pos, cls = self.select.decode(idx) + x, qpe = self.init_queries(lidar_feat, pos, cls) + free_maps(cls) + key = self.keys(lidar_feat) + y = self.decoder(x, qpe, key, taps) + free_maps(key) + heads = self.predict(y) + qheat = self.query_heat(heat_nms, pos) + free_maps(pos) + idx_f = self._indices_tile(idx) + if indices is None: + free_maps(idx) + if taps is not None: + taps.update({"query.feat": x, "decoder.query_pos_embed": qpe, "decoder.out": y}) + else: + free_maps(x, qpe, y) + return {"heads": heads, "query_heat": qheat, "indices": idx_f} + + # ---- host side ----------------------------------------------------------------------------------------- + def unpack_heads(self, heads: Any) -> Dict[str, np.ndarray]: + """The read-back ``heads`` array -> ``{name: (c, K)}`` float32.""" + a = np.asarray(heads, np.float32).reshape(-1, HEAD_PAD)[: self.k] + return {name: np.ascontiguousarray(a[:, s:e].T) for name, s, e in self.head_slices} + + def release(self) -> None: + for m in (self.self_qkv, self.self_out, self.cross_q, self.cross_k, self.cross_v, self.cross_out, + self.ffn1, self.ffn2, self.heads_hidden, self.heads_out, *self.norms): + m.release() + if self._tables is not None: + free_maps(*self._tables.values()) + self._tables = None + + def describe(self) -> Dict[str, Any]: + return {"name": self.name, "cells": self.cells, "classes": self.classes, "proposals": self.k, + "padded_k": self.kp, "dim": self.dim, "heads": [self.heads_self, self.heads_cross], + "head_dim": [self.hd_self, self.hd_cross], + "padded_head_dim": [padded_head_dim(self.hd_self), padded_head_dim(self.hd_cross)], + "scale": [self.scale_self, self.scale_cross], "attn_fp32_acc": self.attn_fp32_acc, + "head_slices": [list(s) for s in self.head_slices], "precision": self.policy.describe(), + "topk": self.select.describe()} + + +# ---------------------------------------------------------------------------------------------- oracle + +class QueryHeadOracle: + """fp32 (or fp64) torch oracle of the LITERAL head (no tables, no padding, no merged heads): the reference of + the device tests. Inputs NCHW ``lidar_feat (1, d, H, W)``, ``heat_nms (1, C, H, W)`` and the class-major + indices of the proposals.""" + + def __init__(self, weights: QueryHeadWeights, *, dtype: str = "float32"): + weights.validate() + self.w = weights + self.dtype = dtype + + def _t(self, a: Any): + import torch + + return torch.as_tensor(np.asarray(a, np.float64)).to(getattr(torch, self.dtype)) + + def _mha(self, a: MHAWeights, q_in, kv_in, v_in): + import torch + + t = self._t + q = q_in @ t(a.wq) + t(a.bq) + k = kv_in @ t(a.wk) + t(a.bk) + v = v_in @ t(a.wv) + t(a.bv) + h, d = int(a.num_heads), a.head_dim + q = q.reshape(-1, h, d).transpose(0, 1) + k = k.reshape(-1, h, d).transpose(0, 1) + v = v.reshape(-1, h, d).transpose(0, 1) + o = torch.softmax((q @ k.transpose(1, 2)) * float(a.scale), dim=-1) @ v + return o.transpose(0, 1).reshape(q_in.shape[0], h * d) @ t(a.wo) + t(a.bo) + + def _ln(self, i: int, x): + import torch + + g, b, eps = self.w.norms[i] + return torch.nn.functional.layer_norm(x, (x.shape[-1],), self._t(g), self._t(b), float(eps)) + + def _posembed(self, mlp: PosEmbedMLP, pos): + import torch + + t = self._t + return torch.relu(pos @ t(mlp.w0) + t(mlp.b0)) @ t(mlp.w1) + t(mlp.b1) + + def __call__(self, lidar_feat: Any, heat_nms: Any, indices: Any) -> Dict[str, np.ndarray]: + """-> ``{"query.feat" (K, d), "decoder.query_pos_embed", "decoder.self_attn", "decoder.cross_attn", + "decoder.out" (K, d), "heads" {name: (c, K)}, "query_heat" (C, K), "query_pos" (K, 2)}``.""" + import torch + + w = self.w + idx = np.asarray(indices).astype(np.int64).reshape(-1)[: w.num_proposals] + pos, cls = idx % w.cells, idx // w.cells + with torch.no_grad(): + feat = self._t(np.asarray(lidar_feat, np.float64).reshape(w.dim, w.cells).T) # (cells, d) + heat = np.asarray(heat_nms, np.float64).reshape(w.num_classes, w.cells) + x = feat[pos] + self._t(w.class_table)[cls] + qpos = self._t(np.asarray(w.bev_pos, np.float64)[pos]) + qpe = self._posembed(w.self_posembed, qpos) + key = feat + self._posembed(w.cross_posembed, self._t(w.bev_pos)) + s = x + qpe + x1 = self._ln(0, x + self._mha(w.self_attn, s, s, s)) + x2 = self._ln(1, x1 + self._mha(w.cross_attn, x1 + qpe, key, key)) + w1, b1, w2, b2 = (self._t(a) for a in w.ffn) + x3 = self._ln(2, x2 + torch.relu(x2 @ w1 + b1) @ w2 + b2) + heads = {} + for h in w.heads: + y = torch.relu(x3 @ self._t(h.w_hidden) + self._t(h.b_hidden)) @ self._t(h.w_out) + self._t(h.b_out) + heads[h.name] = y.T.numpy().astype(np.float32) + + def f(a): + return a.numpy().astype(np.float32) + + return {"query.feat": f(x), "decoder.query_pos_embed": f(qpe), "decoder.self_attn": f(x1), + "decoder.cross_attn": f(x2), "decoder.out": f(x3), "heads": heads, + "query_heat": heat[:, pos].astype(np.float32), "query_pos": f(qpos)} + + +# -------------------------------------------------------------------------------------------- assembly + +def assemble_transfusion(heads: Dict[str, np.ndarray], query_heat: Any, indices: Any, bev_pos: Any, *, + num_classes: int, num_proposals: int, cells: int) -> Dict[str, np.ndarray]: + """TransFusion's (mmdeploy-patched) graph outputs from the head's read-back arrays, in float32 on the host: + ``cls_score0 = query_heat * sigmoid(heads.heatmap)`` ``(1, C, K)``, ``bbox_pred0 = [center + query_pos, + height, dim, vel]`` ``(1, 8, K)``, ``dir_cls_pred0 = rot`` ``(1, 2, K)``; ``query_pos = bev_pos[pos]`` + (float32: never through bf16, S:transfusion:241). ``heads``: :meth:`TransFusionQueryHead.unpack_heads`; + ``query_heat``: the ``[.., Kp, 32]`` rows; ``indices``: the class-major proposal indices.""" + k = int(num_proposals) + idx = np.rint(np.asarray(indices, np.float64).reshape(-1)[:k]).astype(np.int64) + pos = idx % int(cells) + qpos = np.asarray(bev_pos, np.float32)[pos] # (K, 2) + qheat = np.asarray(query_heat, np.float32).reshape(-1, HEAD_PAD)[:k, :int(num_classes)].T + logits = np.asarray(heads["heatmap"], np.float32) + sig = (1.0 / (1.0 + np.exp(-logits.astype(np.float64)))).astype(np.float32) + cls = (qheat * sig).astype(np.float32)[None] + center = (np.asarray(heads["center"], np.float32) + qpos.T).astype(np.float32) + bbox = np.concatenate([center, heads["height"], heads["dim"], heads["vel"]], axis=0).astype(np.float32)[None] + return {"cls_score0": cls, "bbox_pred0": bbox, "dir_cls_pred0": np.asarray(heads["rot"], np.float32)[None]} diff --git a/code/tt_depthpro2/ttaw/nms.py b/code/tt_depthpro2/ttaw/nms.py new file mode 100644 index 0000000000000000000000000000000000000000..2cecbbdcd7971f95abcd11870f28f3654cd61308 --- /dev/null +++ b/code/tt_depthpro2/ttaw/nms.py @@ -0,0 +1,247 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C15 NMS family of the Autoware LiDAR detectors: circle NMS, rotated IoU-BEV NMS with perception_utils semantics, +and the area-based class remapper. + +- :func:`circle_nms` is ``circleNMS`` of ``autoware_lidar_centerpoint/lib/postprocess/circle_nms_kernel.cu:38-142``: + boxes in descending score order; a kept box suppresses every *later* box whose squared BEV centre distance is + strictly below ``threshold^2`` (float32: ``powf(dx, 2) + powf(dy, 2) < powf(thr, 2)``); greedy, class-agnostic. + A threshold <= 0 means 1.5 m in Autoware's config (``centerpoint_config.hpp:83-85,139``): the caller applies that. +- :func:`iou_bev_nms` is ``perception_utils::IouBevNms::apply`` (``perception_utils/src/iou_bev_nms.cpp:132-171``, + universe main 9ceaccf). Object ``t`` is compared with **every** earlier object ``s < t``, kept or suppressed + (S:centerpoint:291-295); pairs with different labels where one is PEDESTRIAN are skipped; pairs whose centre + distance squared exceeds ``search_distance_2d^2`` are skipped; the loop over ``s`` breaks at the first + ``iou > threshold``; ``t`` is kept iff the largest IoU seen is ``<= threshold``. ``sort=False`` (the CenterPoint + node's call) keeps the input order. IoU: the BEV rectangles of ``autoware_utils::toPolygon2d`` intersected + exactly (Sutherland-Hodgman on two convex quadrilaterals, float64), with the area guards 1e-6 (each box and the + intersection) and 0.01 (union). +- :class:`ClassRemapper` is ``perception_utils::DetectionClassRemapper::mapClasses`` + (``perception_utils/src/detection_class_remapper.cpp:54-70``): with ``bev_area = float(length * width)``, the first + destination label (in label order) whose matrix entry allows it and whose ``[min, max]`` contains the area wins. + +numpy only; no side effects on import. +""" +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import Any, List, Mapping, Optional, Sequence + +import numpy as np + +__all__ = [ + "PEDESTRIAN_LABEL", + "circle_nms", + "bev_box_corners", + "polygon_area", + "clip_convex", + "iou_bev", + "iou_bev_nms", + "ClassRemapper", +] + +PEDESTRIAN_LABEL = 7 # autoware_perception_msgs/ObjectClassification PEDESTRIAN + +_MIN_AREA = 1.0e-6 # iou_bev_nms.cpp compute2dIoU kMinArea +_MIN_UNION_AREA = 0.01 # kMinUnionArea + + +def circle_nms(x: Any, y: Any, dist_threshold: float) -> np.ndarray: + """Indices (ascending) of the boxes kept by Autoware's circle NMS. The input must already be in descending + score order (``thrust::sort``); see the module docstring.""" + xs = np.asarray(x, dtype=np.float32) + ys = np.asarray(y, dtype=np.float32) + n = len(xs) + thr2 = np.float32(dist_threshold) * np.float32(dist_threshold) + removed = np.zeros(n, dtype=bool) + keep: List[int] = [] + for i in range(n): + if removed[i]: + continue + keep.append(i) + dx = xs[i + 1:] - xs[i] + dy = ys[i + 1:] - ys[i] + removed[i + 1:] |= (dx * dx + dy * dy) < thr2 + return np.asarray(keep, dtype=np.int64) + + +def bev_box_corners(x: float, y: float, length: float, width: float, yaw: float) -> np.ndarray: + """(4, 2) float64 corners in ``toPolygon2d`` order: (+l/2, +w/2), (-l/2, +w/2), (-l/2, -w/2), (+l/2, -w/2) in + the object frame, rotated by ``yaw`` about the centre (counter-clockwise for positive sizes).""" + c, s = math.cos(yaw), math.sin(yaw) + hl, hw = length / 2.0, width / 2.0 + local = ((hl, hw), (-hl, hw), (-hl, -hw), (hl, -hw)) + return np.array([(x + c * px - s * py, y + s * px + c * py) for px, py in local], dtype=np.float64) + + +def polygon_area(poly: Any) -> float: + """Absolute shoelace area of a polygon (k, 2).""" + p = np.asarray(poly, dtype=np.float64) + if len(p) < 3: + return 0.0 + x, y = p[:, 0], p[:, 1] + return abs(float(np.dot(x, np.roll(y, -1)) - np.dot(np.roll(x, -1), y))) / 2.0 + + +def _signed_area(p: np.ndarray) -> float: + x, y = p[:, 0], p[:, 1] + return float(np.dot(x, np.roll(y, -1)) - np.dot(np.roll(x, -1), y)) / 2.0 + + +def clip_convex(subject: Any, clipper: Any) -> np.ndarray: + """Sutherland-Hodgman: ``subject`` polygon clipped by the convex polygon ``clipper`` (either orientation) -> + (k, 2) float64 intersection polygon (k may be 0).""" + clip = np.asarray(clipper, dtype=np.float64) + if _signed_area(clip) < 0: + clip = clip[::-1] + out = [tuple(p) for p in np.asarray(subject, dtype=np.float64)] + for i in range(len(clip)): + if not out: + break + ax, ay = clip[i] + bx, by = clip[(i + 1) % len(clip)] + inp, out = out, [] + + def inside(p): + return (bx - ax) * (p[1] - ay) - (by - ay) * (p[0] - ax) >= 0.0 + + def cross_point(p, q): + x1, y1, x2, y2 = p[0], p[1], q[0], q[1] + den = (x1 - x2) * (ay - by) - (y1 - y2) * (ax - bx) + if den == 0.0: + return q + t = ((x1 - ax) * (ay - by) - (y1 - ay) * (ax - bx)) / den + return (x1 + t * (x2 - x1), y1 + t * (y2 - y1)) + + prev = inp[-1] + for cur in inp: + if inside(cur): + if not inside(prev): + out.append(cross_point(prev, cur)) + out.append(cur) + elif inside(prev): + out.append(cross_point(prev, cur)) + prev = cur + return np.asarray(out, dtype=np.float64).reshape(-1, 2) + + +def _iou_from(pa: np.ndarray, area_a: float, env_a: np.ndarray, pb: np.ndarray, area_b: float, + env_b: np.ndarray) -> float: + if area_a < _MIN_AREA or area_b < _MIN_AREA: + return 0.0 + if env_a[0] > env_b[2] or env_b[0] > env_a[2] or env_a[1] > env_b[3] or env_b[1] > env_a[3]: + return 0.0 # disjoint envelopes (a speed guard in perception_utils; the intersection would be empty) + inter = polygon_area(clip_convex(pa, pb)) + if inter < _MIN_AREA: + return 0.0 + union = area_a + area_b - inter + if union < _MIN_UNION_AREA: + return 0.0 + return min(1.0, inter / union) + + +def _envelope(p: np.ndarray) -> np.ndarray: + return np.array([p[:, 0].min(), p[:, 1].min(), p[:, 0].max(), p[:, 1].max()]) + + +def iou_bev(a: Sequence[float], b: Sequence[float]) -> float: + """Rotated BEV IoU of two boxes ``(x, y, length, width, yaw)`` with perception_utils' ``compute2dIoU`` guards.""" + pa, pb = bev_box_corners(*a), bev_box_corners(*b) + return _iou_from(pa, polygon_area(pa), _envelope(pa), pb, polygon_area(pb), _envelope(pb)) + + +def iou_bev_nms(x: Any, y: Any, length: Any, width: Any, yaw: Any, labels: Any, *, search_distance_2d: float = 10.0, + iou_threshold: float = 0.1, scores: Optional[Any] = None, sort: bool = False, + pedestrian_label: int = PEDESTRIAN_LABEL) -> np.ndarray: + """Indices of the objects kept by ``IouBevNms::apply`` (module docstring), in processing order. ``labels`` are + ObjectClassification labels; ``yaw`` is the ROS yaw. ``sort=True`` first orders by descending ``scores`` + (``std::stable_sort``).""" + if not math.isfinite(search_distance_2d) or search_distance_2d < 0.0: + raise ValueError("search_distance_2d must be a finite non-negative value") + if not math.isfinite(iou_threshold) or not 0.0 <= iou_threshold <= 1.0: + raise ValueError("iou_threshold must be a finite value between 0 and 1") + xs = np.asarray(x, dtype=np.float64) + n = len(xs) + order = np.arange(n) + if sort: + if scores is None: + raise ValueError("sort=True needs scores") + order = np.argsort(-np.asarray(scores, dtype=np.float64), kind="stable") + ys = np.asarray(y, dtype=np.float64)[order] + xs = xs[order] + ls = np.asarray(length, dtype=np.float64)[order] + ws = np.asarray(width, dtype=np.float64)[order] + yw = np.asarray(yaw, dtype=np.float64)[order] + lab = np.asarray(labels, dtype=np.int64)[order] + polys = [bev_box_corners(xs[i], ys[i], ls[i], ws[i], yw[i]) for i in range(n)] + areas = [polygon_area(p) for p in polys] + envs = [_envelope(p) for p in polys] + sd2 = float(search_distance_2d) * float(search_distance_2d) + keep: List[int] = [] + for t in range(n): + max_iou = 0.0 + for s in range(t): + if lab[t] != lab[s] and (lab[t] == pedestrian_label or lab[s] == pedestrian_label): + continue + dx, dy = xs[t] - xs[s], ys[t] - ys[s] + if not dx * dx + dy * dy <= sd2: + continue + iou = _iou_from(polys[t], areas[t], envs[t], polys[s], areas[s], envs[s]) + max_iou = max(max_iou, iou) + if iou > iou_threshold: + break + if max_iou <= iou_threshold: + keep.append(int(order[t])) + return np.asarray(keep, dtype=np.int64) + + +@dataclass(frozen=True) +class ClassRemapper: + """``DetectionClassRemapper`` with square ``allow`` (bool), ``min_area`` and ``max_area`` matrices indexed + ``[source_label, destination_label]`` over the ObjectClassification labels. Non-finite bounds become + ``DBL_MAX`` (``detection_class_remapper.cpp:43-48``).""" + + allow: np.ndarray + min_area: np.ndarray + max_area: np.ndarray + + @classmethod + def from_lists(cls, allow_remapping_by_area_matrix: Sequence[int], min_area_matrix: Sequence[float], + max_area_matrix: Sequence[float]) -> "ClassRemapper": + """The three flat lists of ``detection_class_remapper.param.yaml`` (row = source, column = destination).""" + if not (len(allow_remapping_by_area_matrix) == len(min_area_matrix) == len(max_area_matrix)): + raise ValueError("Class remapping matrices must have equal sizes.") + n = int(math.isqrt(len(min_area_matrix))) + if n == 0 or n * n != len(min_area_matrix): + raise ValueError("Class remapping matrices must be non-empty and square.") + + def finite(v: Sequence[float]) -> np.ndarray: + a = np.asarray(v, dtype=np.float64) + return np.where(np.isfinite(a), a, np.finfo(np.float64).max).reshape(n, n) + + return cls(np.asarray(allow_remapping_by_area_matrix, dtype=np.int64).reshape(n, n) != 0, + finite(min_area_matrix), finite(max_area_matrix)) + + @classmethod + def from_params(cls, params: Mapping[str, Any]) -> "ClassRemapper": + """From the ``ros__parameters`` mapping of ``detection_class_remapper.param.yaml``.""" + return cls.from_lists(params["allow_remapping_by_area_matrix"], params["min_area_matrix"], + params["max_area_matrix"]) + + @property + def num_labels(self) -> int: + return int(self.allow.shape[0]) + + def apply(self, labels: Any, length: Any, width: Any) -> np.ndarray: + """New labels (uint8) for objects with ``labels`` and BEV ``length`` x ``width``.""" + lab = np.asarray(labels, dtype=np.int64).copy() + area = (np.asarray(length, dtype=np.float64) * np.asarray(width, dtype=np.float64)).astype(np.float32) + area = area.astype(np.float64) + for i in range(len(lab)): + src = int(lab[i]) + if src < 0 or src >= self.num_labels: + continue + for dst in range(self.num_labels): + if self.allow[src, dst] and self.min_area[src, dst] <= area[i] <= self.max_area[src, dst]: + lab[i] = dst + break + return lab.astype(np.uint8) diff --git a/code/tt_depthpro2/ttaw/ops/__init__.py b/code/tt_depthpro2/ttaw/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0e5e3c82a25bd65d8a03b4e4354929c839d9e545 --- /dev/null +++ b/code/tt_depthpro2/ttaw/ops/__init__.py @@ -0,0 +1,28 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Custom-op helpers. Kernel ``.cpp`` / ``.hpp`` files are package data under ``ops/kernels/`` (shipped through +``source.extra_code`` and ``[tool.setuptools.package-data]``), and are always referenced by absolute path, because +tt-metal resolves a relative kernel path against the CWD, ``TT_METAL_KERNEL_PATH`` and ``TT_METAL_HOME`` first +(TT_PLATFORM.md section 5.1). The C17-C23 op modules and the K1-K11 kernels of PLAN.md section 1.3 are added here +by the first port that needs them, with a numpy oracle test and the hang protocol of PLAN.md section 4.4. + +Op modules (import them explicitly; this package imports none of them): ``conv`` (C17 conv builders), ``upsample`` +(C18 up-sampling and interpolation), ``attention`` (C20 SDPA wrapper), ``gather`` (C19 row gathers), ``topk`` (C21 +top-k selection), ``heatmap`` (C22 heatmap local max), ``deform`` (C23 grid_sample helpers), ``segment`` (K1 +``segment_reduce``: the first ``generic_op`` kernel, ``kernels/segment_reduce_dm.cpp``). +""" +from __future__ import annotations + +import os + +__all__ = ["KERNEL_DIR", "kernel_path"] + +KERNEL_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels") + + +def kernel_path(name: str, base: str = KERNEL_DIR) -> str: + """Absolute path of a kernel source shipped with the package (``kernel_path("segment_max_reader.cpp")``). + Raises ``FileNotFoundError`` early instead of tt-metal's "doesn't exist in any of the searched paths".""" + path = os.path.join(base, name) + if not os.path.isfile(path): + raise FileNotFoundError(f"kernel source {path} is missing (not shipped as package data?)") + return path diff --git a/code/tt_depthpro2/ttaw/ops/attention.py b/code/tt_depthpro2/ttaw/ops/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..7776d9ba671a7afd7ccc787152e7bb95e43dc9ec --- /dev/null +++ b/code/tt_depthpro2/ttaw/ops/attention.py @@ -0,0 +1,386 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C20: attention on the p150 through ``ttnn.transformer.scaled_dot_product_attention`` (PLAN.md 1.2 C20, probe P7). + +SDPA has three silent traps (common/PROBES.md P7; ``probes/g4-attention-gridsample-msda.md``): + +- ``is_causal`` defaults to True: with Sq == Sk it silently applies a causal mask, with Sq != Sk it is rejected; +- the default ``scale`` is ``1/sqrt(padded head_dim)``: after a 16 -> 32 head padding it is wrong (PCC 0.979); +- the default program config (32/32 chunks) is 2.5-7x slower everywhere and inaccurate over >= 32k keys. + +:func:`sdpa` is the only way the ports call the op: ``is_causal=False`` always, ``scale`` is a required keyword, +and a ``program_config`` is always passed (chunk sizes from :func:`chunk_config`, the P7 table). Without a mask, +pass the logical, unaligned Sq / Sk: the op pads to its chunks and masks its own padding element by element. A user +mask is an additive bf16 TILE tensor **in DRAM**, ``[1|B, 1|H, Sq, Sk]``; ``-inf`` is safe, also when a whole first +key chunk is masked (P7). + +**A user mask needs a tile-aligned Sk** (found by the Diffusion Planner port, 2026-10-07): with a mask, the reader +fills only the key *tiles* past ``ceil(Sk / 32)`` with ``-inf`` and reads the last partial tile from the mask +itself, whose tile padding is 0 after a host tilize (``reader_interleaved.cpp``, "Mask read"). The up to 31 padded +keys then join the softmax with score ``q . k_pad`` and value ``v_pad``: rel-L2 0.18 instead of 0.025 at 321 x 321 +with 89 valid keys, 0.06 at P7's masked 564 x 564. :func:`sdpa` therefore refuses a mask with ``Sk % 32 != 0``: +give K / V a tile-aligned key count (:func:`aligned_keys`; the extra keys are masked with ``-inf`` in the mask, +``key_bias(padded_validity, sq)``), which costs nothing because the tiles are padded anyway. + +Head layout. The op wants ``[B, H, S, D]`` bf16 TILE interleaved tensors with ``D`` a multiple of 32 and no padding on +B / H / D. :func:`split_heads` / :func:`split_qkv` / :func:`split_q_kv` turn projection outputs ``[B, 1, S, H*D]`` +into heads (``ttnn.experimental.nlp_create_qkv_heads``, one program, logical S kept), and ``sdpa(..., +concat_heads=True)`` (the op's ``output_concat_heads``) or :func:`merge_heads` go back to ``[B, 1, S, H*D]``. +A head dim below 32 (16 in TransFusion / BEVFusion / PTv3) is zero-padded *in the weights* +(:func:`pad_head_columns` on the Q / K / V projections, :func:`pad_head_rows` on the output projection): exact +(padded output columns are 0, P7) and free at run time; pass ``scale=1/sqrt(logical head dim)``. + +Masks. :func:`key_bias` builds ``[1, 1, Sq, Sk]`` (0 for valid keys, ``-inf`` otherwise) on the host; inside a +trace :func:`expand_key_bias` repeats a persistent ``[1, 1, 1, Sk]`` bias row (:func:`key_bias_row`) to +``[1, 1, Sq, Sk]`` in DRAM (one program, the upload shrinks from Sq * Sk to Sk values). + +Fallback. :func:`attention_matmul` is plain ``softmax(scale Q K^T + bias) V`` with matmuls (for dtypes or layouts the +op rejects, e.g. fp32 attention); it needs a tile-aligned Sk (pad the keys and mask them with ``-inf``). +:func:`attention_reference` is the float64 numpy oracle of both. + +Importing this module never imports ttnn (ttaw rule); ttnn is imported inside the functions that need it. +""" +from __future__ import annotations + +import math +from typing import Any, Dict, Optional, Sequence, Tuple + +import numpy as np + +__all__ = [ + "aligned_keys", + "HEAD_DIM_MULTIPLE", + "PROGRAM_CONFIG_MIN_SK", + "CHUNK_TABLE", + "padded_head_dim", + "chunk_config", + "sdpa_program_config", + "sdpa_compute_config", + "sdpa", + "split_heads", + "split_qkv", + "split_q_kv", + "merge_heads", + "key_bias", + "key_bias_row", + "expand_key_bias", + "pad_head_dim", + "pad_head_columns", + "pad_head_rows", + "attention_reference", + "attention_matmul", +] + +HEAD_DIM_MULTIPLE = 32 # SDPA rejects a padded head dim ("Padding is not supported on the head_dim dimension") +TILE = 32 +# P7: from about 1,000 keys on, the default 32/32 chunks are 2.5-7x slower; this wrapper passes a config always. +PROGRAM_CONFIG_MIN_SK = 1000 + +# Exact (Sq, Sk) shapes measured on the p150b (ETH, 12x10): (q_chunk, k_chunk) and the evidence. Shapes not listed +# use the Sk-range rules of :func:`chunk_config`. Ports add their measured shapes here (with the log). +CHUNK_TABLE: Dict[Tuple[int, int], Tuple[int, int, str]] = { + (500, 500): (128, 128, "P7 tf_self 0.029 ms (default 0.047)"), + (512, 512): (512, 512, "P7 pt_patch_s0/s4 0.172-0.222 ms (q128 k128 0.413-0.571)"), + (564, 564): (64, 64, "P7 dp_fusion_masked 0.058 ms (default 0.094, q128 k128 0.158)"), + (321, 564): (64, 64, "P7 dp_cross 0.029 ms (default 0.030)"), + (576, 576): (64, 64, "DP fusion, masked: 0.061-0.092 ms (q32 k64 0.117, q32 k32 0.129, q128 k128 0.275)"), + (352, 352): (64, 64, "DP DiT self, masked: 0.063 ms (q64 k128 0.059, q32 k32 0.080, q128 k128 0.071)"), + (352, 564): (64, 64, "DP DiT cross: 0.033-0.043 ms (q32 k32 0.035, q128 k128 0.052, q64 k128 0.077)"), + (900, 1668): (64, 128, "P7 sp_self 0.052 ms (default 0.139)"), + (900, 6000): (64, 512, "P7 sp_cross 0.106 ms (default 0.469)"), +} + + +def padded_head_dim(head_dim: int, multiple: int = HEAD_DIM_MULTIPLE) -> int: + """The head dim SDPA sees: ``head_dim`` rounded up to a multiple of 32.""" + if head_dim <= 0: + raise ValueError(f"head_dim must be positive, got {head_dim}") + return -(-int(head_dim) // multiple) * multiple + + +def aligned_keys(n: int, multiple: int = TILE) -> int: + """The tile-aligned key count a masked attention over ``n`` real keys runs on (the extra keys are masked).""" + if n <= 0: + raise ValueError(f"key count must be positive, got {n}") + return -(-int(n) // multiple) * multiple + + +def chunk_config(sq: int, sk: int) -> Tuple[int, int]: + """``(q_chunk, k_chunk)`` for logical ``Sq`` x ``Sk`` (multiples of 32, as the op requires). + + Exact shapes come from :data:`CHUNK_TABLE`. Otherwise, by key length (P7: chunk sizes are what matters for + long keys; q64 keeps ``B * H * Sq / 64`` work units near the 120 cores at Sq ~ 500-900): + Sk >= 16,384 -> q64 k1024 (P7 tf / bf / pt cross 0.45-0.88 ms; q64 k512 + ``fp32_acc`` halves the max error at + ~1.4x the time); Sk >= 4,096 -> q64 k512; Sk >= 1,000 -> q64 k128; shorter keys -> q64 k64 (32 when the + sequence fits one tile). + """ + sq, sk = int(sq), int(sk) + if sq <= 0 or sk <= 0: + raise ValueError(f"sequence lengths must be positive, got Sq={sq}, Sk={sk}") + if (sq, sk) in CHUNK_TABLE: + q, k, _ = CHUNK_TABLE[(sq, sk)] + return q, k + q = 32 if sq <= TILE else 64 + if sk >= 16384: + return q, 1024 + if sk >= 4096: + return q, 512 + if sk >= PROGRAM_CONFIG_MIN_SK: + return q, 128 + return q, (32 if sk <= TILE else 64) + + +def sdpa_program_config(device: Any, sq: int, sk: int, *, q_chunk: Optional[int] = None, k_chunk: Optional[int] = None, + exp_approx_mode: Optional[bool] = None): + """``ttnn.SDPAProgramConfig`` over the device's whole compute grid (read from the device, never hard-coded) + with the :func:`chunk_config` chunks unless ``q_chunk`` / ``k_chunk`` are given.""" + import ttnn + + q_default, k_default = chunk_config(sq, sk) + q_chunk = int(q_chunk or q_default) + k_chunk = int(k_chunk or k_default) + for name, value in (("q_chunk", q_chunk), ("k_chunk", k_chunk)): + if value <= 0 or value % TILE: + raise ValueError(f"{name}={value}: must be a positive multiple of {TILE}") + return ttnn.SDPAProgramConfig(compute_with_storage_grid_size=device.compute_with_storage_grid_size(), + q_chunk_size=q_chunk, k_chunk_size=k_chunk, exp_approx_mode=exp_approx_mode) + + +def sdpa_compute_config(*, fp32_acc: bool = False, fidelity: str = "HiFi2", approx: bool = True): + """Explicit SDPA compute config. The default equals the op's own (HiFi2, bf16 DST, approximate exp): P7 found + neither HiFi4 nor exact exp more accurate; ``fp32_acc=True`` (the op's standard instead of its streaming kernel) + halves the max error (0.11 -> 0.056 over 36k keys) at 1.35-1.45x the time.""" + from ..precision import compute_kernel_config + + return compute_kernel_config(fidelity, fp32_acc=fp32_acc, approx=approx) + + +def _seq(t: Any) -> int: + return int(t.shape[-2]) + + +def sdpa(q: Any, k: Any, v: Any, *, scale: float, attn_mask: Any = None, program_config: Any = "auto", + compute_kernel_config: Any = None, fp32_acc: bool = False, concat_heads: bool = False, + memory_config: Any = None): + """Non-causal scaled dot-product attention ``softmax(scale * Q K^T + attn_mask) V``. + + ``q`` ``[B, H, Sq, D]``, ``k`` / ``v`` ``[B, Hkv, Sk, D]`` (bf16 / bfp8 / bfp4, TILE, interleaved, D a multiple of + 32); ``scale`` is required: ``1/sqrt(logical head dim)`` (never the op's padded-head default). ``attn_mask``: + additive ``[1|B, 1|H, Sq, Sk]`` bf16 TILE tensor in DRAM, or None; with a mask ``Sk`` must be a multiple of 32 + (module docstring). ``program_config``: ``"auto"`` (the + :func:`chunk_config` chunks over the whole grid), an ``SDPAProgramConfig``, or None (op default; refused once + Sk >= :data:`PROGRAM_CONFIG_MIN_SK`, P7). ``compute_kernel_config`` overrides :func:`sdpa_compute_config` + (``fp32_acc``). ``concat_heads=True`` returns ``[B, 1, Sq, H*D]`` instead of ``[B, H, Sq, D]`` (no separate + concat program). Returns the device tensor. + """ + import ttnn + + scale = float(scale) + if not math.isfinite(scale) or scale <= 0.0: + raise ValueError(f"scale must be a positive finite float, got {scale!r}") + if len(q.shape) != 4 or len(k.shape) != 4 or len(v.shape) != 4: + raise ValueError(f"sdpa expects [B, H, S, D] tensors, got q{tuple(q.shape)} k{tuple(k.shape)} " + f"v{tuple(v.shape)}") + d = int(q.shape[-1]) + if d % HEAD_DIM_MULTIPLE: + raise ValueError(f"head dim {d} is not a multiple of {HEAD_DIM_MULTIPLE}: zero-pad it in the projection " + "weights (pad_head_columns / pad_head_rows) and pass scale=1/sqrt(logical head dim)") + sq, sk = _seq(q), _seq(k) + if attn_mask is not None and sk % TILE: + raise ValueError(f"a user mask needs a tile-aligned key count (Sk={sk}): the op masks the padded keys of the " + "last partial tile only through the mask's own tile padding (0 after a host tilize), so " + f"they would join the softmax. Run on aligned_keys({sk}) = {aligned_keys(sk)} keys and mask " + "the extra ones with -inf (key_bias on the padded validity)") + if isinstance(program_config, str): + if program_config != "auto": + raise ValueError(f"program_config={program_config!r}: expected 'auto', a config object or None") + program_config = sdpa_program_config(q.device(), sq, sk) + elif program_config is None and sk >= PROGRAM_CONFIG_MIN_SK: + raise ValueError(f"Sk={sk} >= {PROGRAM_CONFIG_MIN_SK}: the op's default 32/32 chunks are slow and inaccurate " + "for long keys (probe P7); pass program_config='auto' or an SDPAProgramConfig") + if compute_kernel_config is None: + compute_kernel_config = sdpa_compute_config(fp32_acc=fp32_acc) + kwargs: Dict[str, Any] = {} + if concat_heads: + kwargs["output_concat_heads"] = True + return ttnn.transformer.scaled_dot_product_attention( + q, k, v, attn_mask=attn_mask, is_causal=False, scale=scale, memory_config=memory_config, + program_config=program_config, compute_kernel_config=compute_kernel_config, **kwargs) + + +# ---------------------------------------------------------------------------------------------------- heads + +def _check_4d_heads(x: Any, what: str) -> None: + if len(x.shape) != 4 or int(x.shape[1]) != 1: + raise ValueError(f"{what} must be [B, 1, S, width] (a 4-D projection output), got {tuple(x.shape)}") + + +def split_heads(x: Any, num_heads: int, *, memory_config: Any = None): + """``[B, 1, S, H*D]`` -> ``[B, H, S, D]`` (one ``nlp_create_qkv_heads`` program with no K / V heads; the logical + S is kept, so unaligned sequences stay unaligned for :func:`sdpa`).""" + import ttnn + + _check_4d_heads(x, "split_heads input") + width = int(x.shape[-1]) + if width % num_heads or (width // num_heads) % HEAD_DIM_MULTIPLE: + raise ValueError(f"width {width} does not split into {num_heads} heads of a multiple of {HEAD_DIM_MULTIPLE}") + out, _, _ = ttnn.experimental.nlp_create_qkv_heads(x, num_heads=num_heads, num_kv_heads=0, + transpose_k_heads=False, memory_config=memory_config) + return out + + +def split_qkv(qkv: Any, num_heads: int, *, num_kv_heads: Optional[int] = None, memory_config: Any = None): + """Fused ``[B, 1, S, (H + 2 Hkv) * D]`` (Q | K | V column blocks, heads contiguous) -> ``(q, k, v)`` + ``[B, H|Hkv, S, D]`` in one program (K not transposed).""" + import ttnn + + _check_4d_heads(qkv, "split_qkv input") + kv_heads = num_heads if num_kv_heads is None else int(num_kv_heads) + width = int(qkv.shape[-1]) + if width % (num_heads + 2 * kv_heads) or (width // (num_heads + 2 * kv_heads)) % HEAD_DIM_MULTIPLE: + raise ValueError(f"width {width} does not split into {num_heads} + 2 x {kv_heads} heads of a multiple of " + f"{HEAD_DIM_MULTIPLE}") + return ttnn.experimental.nlp_create_qkv_heads(qkv, num_heads=num_heads, num_kv_heads=kv_heads, + transpose_k_heads=False, memory_config=memory_config) + + +def split_q_kv(q: Any, kv: Any, num_heads: int, *, num_kv_heads: Optional[int] = None, memory_config: Any = None): + """Separate ``q`` ``[B, 1, S, H*D]`` and ``kv`` ``[B, 1, S, 2*Hkv*D]`` (K | V column blocks) with the SAME S + (self-attention with Q and K / V from different inputs, e.g. a pre-LN Q next to an un-normalised K / V) + -> ``(q, k, v)`` heads in one program. Cross-attention with another key length: :func:`split_heads` each.""" + import ttnn + + _check_4d_heads(q, "split_q_kv q") + _check_4d_heads(kv, "split_q_kv kv") + if int(q.shape[-2]) != int(kv.shape[-2]): + raise ValueError(f"split_q_kv needs the same sequence length (Q {q.shape[-2]}, K/V {kv.shape[-2]})") + kv_heads = num_heads if num_kv_heads is None else int(num_kv_heads) + return ttnn.experimental.nlp_create_qkv_heads(q, kv, num_heads=num_heads, num_kv_heads=kv_heads, + transpose_k_heads=False, memory_config=memory_config) + + +def merge_heads(x: Any, *, memory_config: Any = None): + """``[B, H, S, D]`` -> ``[B, 1, S, H*D]`` (``nlp_concat_heads``). Prefer ``sdpa(..., concat_heads=True)``.""" + import ttnn + + if len(x.shape) != 4: + raise ValueError(f"merge_heads expects [B, H, S, D], got {tuple(x.shape)}") + return ttnn.experimental.nlp_concat_heads(x, memory_config=memory_config) + + +# ---------------------------------------------------------------------------------------------------- masks + +def key_bias_row(valid: Sequence[bool], *, dtype: Any = np.float32) -> np.ndarray: + """``[1, 1, 1, Sk]`` additive key bias: 0 for valid keys, ``-inf`` for masked ones (bf16-exact values).""" + v = np.asarray(valid, dtype=bool).reshape(-1) + if v.size == 0: + raise ValueError("key_bias_row: empty validity vector") + if not v.any(): + raise ValueError("key_bias_row: every key is masked (the softmax of a fully masked row is undefined)") + return np.where(v, 0.0, -np.inf).astype(dtype).reshape(1, 1, 1, -1) + + +def key_bias(valid: Sequence[bool], sq: int, *, dtype: Any = np.float32) -> np.ndarray: + """``[1, 1, Sq, Sk]`` additive key mask for :func:`sdpa` (identical rows), built on the host. Upload it as a + bf16 TILE tensor in DRAM (the op's requirement), or keep a :func:`key_bias_row` input and expand it on the + device with :func:`expand_key_bias`.""" + row = key_bias_row(valid, dtype=dtype) + return np.ascontiguousarray(np.broadcast_to(row, (1, 1, int(sq), row.shape[-1]))) + + +def expand_key_bias(row: Any, sq: int, *, memory_config: Any = None): + """Device-side :func:`key_bias`: repeat a ``[1, 1, 1, Sk]`` bf16 TILE bias row to ``[1, 1, Sq, Sk]`` in DRAM + (one program; traceable).""" + import ttnn + + if len(row.shape) != 4 or int(row.shape[-2]) != 1: + raise ValueError(f"expand_key_bias expects a [1, 1, 1, Sk] row, got {tuple(row.shape)}") + return ttnn.repeat(row, [1, 1, int(sq), 1], + memory_config=ttnn.DRAM_MEMORY_CONFIG if memory_config is None else memory_config) + + +# ---------------------------------------------------------------------------------------------------- head padding + +def pad_head_dim(x: Any, padded: Optional[int] = None) -> np.ndarray: + """Zero-pad the last (head) dim of a host array ``[..., D]`` to ``padded`` (default :func:`padded_head_dim`).""" + a = np.asarray(x) + d = a.shape[-1] + p = padded_head_dim(d) if padded is None else int(padded) + if p < d: + raise ValueError(f"padded head dim {p} < head dim {d}") + if p == d: + return a + return np.pad(a, [(0, 0)] * (a.ndim - 1) + [(0, p - d)]) + + +def pad_head_columns(w: Any, b: Any, num_heads: int, head_dim: int, + padded: Optional[int] = None) -> Tuple[np.ndarray, Optional[np.ndarray]]: + """Projection ``[in, H*D]`` (``y = x @ w + b``) -> ``[in, H*Dp]`` with zero columns after each head's D (and the + bias likewise), so the projection itself emits padded heads (exact: the padded columns are 0).""" + w = np.asarray(w) + p = padded_head_dim(head_dim) if padded is None else int(padded) + if w.shape[-1] != num_heads * head_dim: + raise ValueError(f"weight has {w.shape[-1]} columns, expected {num_heads} x {head_dim}") + wh = w.reshape(w.shape[:-1] + (num_heads, head_dim)) + wp = np.zeros(w.shape[:-1] + (num_heads, p), w.dtype) + wp[..., :head_dim] = wh + bp = None + if b is not None: + b = np.asarray(b).reshape(num_heads, head_dim) + bp = np.zeros((num_heads, p), b.dtype) + bp[:, :head_dim] = b + bp = bp.reshape(-1) + return wp.reshape(w.shape[:-1] + (num_heads * p,)), bp + + +def pad_head_rows(w: Any, num_heads: int, head_dim: int, padded: Optional[int] = None) -> np.ndarray: + """Output projection ``[H*D, out]`` -> ``[H*Dp, out]`` with zero rows at each head's padded positions, matching + the ``[.., H*Dp]`` concatenated-heads output of a padded attention.""" + w = np.asarray(w) + p = padded_head_dim(head_dim) if padded is None else int(padded) + if w.shape[0] != num_heads * head_dim: + raise ValueError(f"weight has {w.shape[0]} rows, expected {num_heads} x {head_dim}") + wp = np.zeros((num_heads, p) + w.shape[1:], w.dtype) + wp[:, :head_dim] = w.reshape((num_heads, head_dim) + w.shape[1:]) + return wp.reshape((num_heads * p,) + w.shape[1:]) + + +# ---------------------------------------------------------------------------------------------------- oracle / fallback + +def attention_reference(q: Any, k: Any, v: Any, *, scale: float, bias: Any = None) -> np.ndarray: + """float64 numpy ``softmax(scale Q K^T + bias) V`` over ``[B, H, S, D]`` arrays (K / V heads broadcast when + ``Hkv`` divides ``H``); ``bias`` broadcasts to ``[B, H, Sq, Sk]`` (``-inf`` allowed).""" + q = np.asarray(q, np.float64) + k = np.asarray(k, np.float64) + v = np.asarray(v, np.float64) + if k.shape[1] != q.shape[1]: + rep = q.shape[1] // k.shape[1] + k, v = np.repeat(k, rep, axis=1), np.repeat(v, rep, axis=1) + s = np.einsum("bhqd,bhkd->bhqk", q, k) * float(scale) + if bias is not None: + s = s + np.asarray(bias, np.float64) + s = s - s.max(axis=-1, keepdims=True) + p = np.exp(s) + p /= p.sum(axis=-1, keepdims=True) + return np.einsum("bhqk,bhkd->bhqd", p, v) + + +def attention_matmul(q: Any, k: Any, v: Any, *, scale: float, attn_mask: Any = None, + compute_kernel_config: Any = None): + """Small-MHA fallback for what :func:`sdpa` rejects (e.g. fp32 Q / K / V): ``softmax(scale Q K^T + mask) V`` + with two matmuls. ``q`` ``[B, H, Sq, D]``, ``k`` / ``v`` ``[B, H, Sk, D]`` with a tile-aligned ``Sk`` (pad the + keys and mask the padding with ``-inf``: a softmax over tile padding would include it). Materialises the + ``[B, H, Sq, Sk]`` scores, so keep it for small shapes.""" + import ttnn + + from ..precision import compute_kernel_config as ckc + + sk = int(k.shape[-2]) + if sk % TILE: + raise ValueError(f"attention_matmul needs a tile-aligned Sk (got {sk}): pad the keys and mask them") + cfg = compute_kernel_config if compute_kernel_config is not None else ckc("HiFi4", fp32_acc=True) + scores = ttnn.matmul(q, k, transpose_b=True, compute_kernel_config=cfg) + scores = ttnn.multiply(scores, float(scale)) + if attn_mask is not None: + scores = ttnn.add(scores, attn_mask) + probs = ttnn.softmax(scores, dim=-1, numeric_stable=True, compute_kernel_config=cfg) + return ttnn.matmul(probs, v, compute_kernel_config=cfg) diff --git a/code/tt_depthpro2/ttaw/ops/conv.py b/code/tt_depthpro2/ttaw/ops/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..4ee4ffd6c87b24912b49ce7006353cd787869932 --- /dev/null +++ b/code/tt_depthpro2/ttaw/ops/conv.py @@ -0,0 +1,771 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C17: conv2d builders for NHWC feature maps (PLAN.md section 1.2 row C17; probes P5 and P14, common/PROBES.md). + +A conv layer of a port is built once from host weights and called on device feature maps, eagerly for the warm-up +and then inside trace captures. What every builder here guarantees: + +- **Weights prepared once.** The first call hands the host weights to ``ttnn.conv2d`` (which prepares them for the + chosen sharding and moves them to the device, a host write); the prepared device tensors are kept per input spec + and reused, so a traced call never writes from the host ("Writes are not supported during trace capture", + RP section 1.4). Call each layer once eagerly before capturing (``TraceRunner`` warm-up does). +- **Explicit precision.** ``compute_config`` comes from :mod:`..precision` (default :data:`CONV_PRECISION`: HiFi4 + + fp32 accumulation + packer L1 accumulation, exact SFPU activations; never ttnn's implicit defaults; without the L1 + accumulation the partial sums of wide convs round to bf16 between inner blocks). Weights default to bf16 + (``Precision.weights`` selects bfp8); ``output_dtype`` may be float32 (e.g. heads whose logits feed thresholds). +- **Fused bias + activation** in the conv epilogue: ``relu`` (packer), ``relu6`` / ``silu`` / ``gelu`` / + ``sigmoid`` (SFPU). RELU6 is verified on the device (P5: output in [0, 6], PCC >= 0.99997). HARDSWISH is refused: + the fused form is silently skipped on this tree (P5; apply ``ttnn.hardswish`` as a separate op). +- **Grid from the device.** Nothing here hard-codes 12x10 / 11x10: ttnn's auto-sharding reads + ``device.compute_with_storage_grid_size()``; explicit shard overrides go through ``conv_config``. +- **Memory placement.** ``slicing="auto"`` keeps ttnn's rule: a DRAM input runs the DRAM-sliced path with automatic + slice counts (P14: every accepted config captures and replays bit-exactly; explicit counts are often rejected, so + never hard-code them) and writes a DRAM-interleaved output; an L1 input runs the L1 path. 1x1 stride-1 convs are + matmuls and always run the L1 path; ``output_memory_config`` (default ``"dram"``) brings their output back to DRAM + so a graph can keep every activation in DRAM between ops (the robust layout of a first port; L1 residency is an + optimization). Feed large-kernel convs TILE tensors (``[1, 1, N*H*W, C]``, what a producing conv writes): from + row-major DRAM they cost 2x (P5: 926 vs 482 us for YOLOX's 12 large-kernel convs). + +Feature maps travel as :class:`FeatureMap` (device tensor + logical N, H, W, C), because ttnn's flattened +``[1, 1, N*H*W, C]`` layout no longer carries the spatial size. + +Builders: :class:`Conv2d` (any kernel / stride / padding / dilation / groups), :class:`KSplitConv` +(``conv(concat(x_1..x_n))`` as ``sum_i conv_i(x_i)`` without building the concat; P14: 1.7-4.1x faster and more +accurate for CenterPoint / PointPainting / FRNet's wide concats), :class:`ConvTranspose2d` for kernel == stride +(P5: k = 2 -> ``ttnn.conv_transpose2d``; k >= 3 -> ``ttnn.linear`` + depth-to-space, 5x faster at k = 4), and the +host helpers :func:`merge_sibling_convs` (one conv for sibling heads that read the same input) / +:func:`split_k_weights`. Glue: :func:`concat_channels`, :func:`split_channels`, :func:`residual_add`, +:func:`apply_activation`, :func:`fmap_from_numpy` / :func:`fmap_to_numpy` (NCHW <-> device NHWC). +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Sequence, Tuple, Union + +import numpy as np + +from ..precision import Precision +from ..tensors import dtype_name, round_to_bf16, ttnn_dtype + +__all__ = [ + "CONV_PRECISION", + "FUSED_ACTIVATIONS", + "BINARY_FUSED_ACTIVATIONS", + "FeatureMap", + "Conv2d", + "KSplitConv", + "ConvTranspose2d", + "normalize_activation", + "unary_with_param", + "apply_activation", + "conv_padding", + "conv_out_hw", + "merge_sibling_convs", + "split_k_weights", + "concat_channels", + "split_channels", + "residual_add", + "fmap_from_numpy", + "fmap_to_numpy", + "is_dram", +] + +# Default precision of every builder here: HiFi4 + fp32 accumulation + packer L1 accumulation. Without +# ``packer_l1_acc`` a conv whose inner dim spans several blocks keeps its partial sums between blocks in the OUTPUT +# dtype (bf16) (conv2d_op_program_factory_common.cpp:175-178: partials CB = output dtype unless packer_l1_acc), which +# costs accuracy on wide convs; with it the partials stay fp32 (C17 device test, logs/ttaw/c17_c18_device_results.json). +CONV_PRECISION = "HiFi4+fp32+l1acc" + +# Activations a conv epilogue applies correctly on this tree (P5 / P14 on the device). HARDSWISH is NOT among them: +# a fused HARDSWISH compiles to nothing (unary_op_utils.cpp:964-965, probe P5) and returns the un-activated result. +FUSED_ACTIVATIONS = ("relu", "relu6", "silu", "gelu", "sigmoid") +# Activations fused into ``ttnn.add(..., activations=[...])`` verified on the device (P5: RELU6 on the clip6 add). +BINARY_FUSED_ACTIVATIONS = ("relu", "relu6") +_REFUSED = { + "hardswish": "a fused HARDSWISH is silently skipped by ttnn on this tree (probe P5): use activation=None and " + "ttnn.hardswish / ttnn.unary_chain([HARDSWISH]) as a separate op", +} + +ActivationSpec = Optional[str] + + +def normalize_activation(activation: Any) -> ActivationSpec: + """``None`` / ``"none"`` / ``"linear"`` / ``"identity"`` -> None; a fused activation name -> its lower-case name. + Raises ``ValueError`` for HARDSWISH (silently skipped when fused, P5) and for unknown names.""" + if activation is None: + return None + name = str(activation).strip().lower() + if name in ("", "none", "linear", "identity"): + return None + if name in _REFUSED: + raise ValueError(f"activation {activation!r}: {_REFUSED[name]}") + if name not in FUSED_ACTIVATIONS: + raise ValueError(f"activation {activation!r}: expected None or one of {FUSED_ACTIVATIONS}") + return name + + +def unary_with_param(activation: Any): + """The ``ttnn.UnaryWithParam`` of a fused activation (None for no activation). GELU is the exact (erf) form.""" + import ttnn + + name = normalize_activation(activation) + if name is None: + return None + if name == "gelu": + return ttnn.UnaryWithParam(ttnn.UnaryOpType.GELU, 0.0) + return ttnn.UnaryWithParam(getattr(ttnn.UnaryOpType, name.upper())) + + +def apply_activation(tensor: Any, activation: Any): + """The activation as a separate (unfused) ttnn op; identity for None.""" + import ttnn + + name = normalize_activation(activation) + if name is None: + return tensor + if name == "relu6": + return ttnn.relu6(tensor) + if name == "gelu": + return ttnn.gelu(tensor, fast_and_approximate_mode=False) + return getattr(ttnn, name)(tensor) + + +def _pair(value: Union[int, Sequence[int]], what: str) -> Tuple[int, int]: + if isinstance(value, (int, np.integer)): + return int(value), int(value) + v = tuple(int(x) for x in value) + if len(v) != 2: + raise ValueError(f"{what} must be an int or a pair, got {value!r}") + return v + + +def conv_padding(kernel: Tuple[int, int], padding: Any = "same", dilation: Tuple[int, int] = (1, 1) + ) -> Tuple[int, int, int, int]: + """Padding as (top, bottom, left, right). ``"same"``: ``dilation * (k // 2)`` on every side (odd kernels; the + "same" padding of stride-1 convs in every model here). An int, a pair (h, w) or a 4-tuple pass through.""" + if isinstance(padding, str): + if padding != "same": + raise ValueError(f"padding {padding!r}: expected 'same', an int, a pair or (top, bottom, left, right)") + if kernel[0] % 2 == 0 or kernel[1] % 2 == 0: + raise ValueError(f"'same' padding needs odd kernels, got {kernel}") + ph, pw = dilation[0] * (kernel[0] // 2), dilation[1] * (kernel[1] // 2) + return ph, ph, pw, pw + if isinstance(padding, (int, np.integer)): + p = int(padding) + return p, p, p, p + p = tuple(int(x) for x in padding) + if len(p) == 2: + return p[0], p[0], p[1], p[1] + if len(p) == 4: + return p # type: ignore[return-value] + raise ValueError(f"padding {padding!r}: expected 'same', an int, a pair or (top, bottom, left, right)") + + +def conv_out_hw(hw: Tuple[int, int], kernel: Tuple[int, int], stride: Tuple[int, int], + padding: Tuple[int, int, int, int], dilation: Tuple[int, int] = (1, 1)) -> Tuple[int, int]: + """Output size of a convolution (floor), as torch / ttnn compute it.""" + h = (hw[0] + padding[0] + padding[1] - dilation[0] * (kernel[0] - 1) - 1) // stride[0] + 1 + w = (hw[1] + padding[2] + padding[3] - dilation[1] * (kernel[1] - 1) - 1) // stride[1] + 1 + if h <= 0 or w <= 0: + raise ValueError(f"conv of a {hw} input with kernel {kernel}, stride {stride}, padding {padding} is empty") + return h, w + + +def is_dram(tensor_or_config: Any) -> bool: + """True when a device tensor (or a memory config) lives in DRAM.""" + import ttnn + + mc = tensor_or_config.memory_config() if hasattr(tensor_or_config, "memory_config") else tensor_or_config + bt = getattr(mc, "buffer_type", None) + if bt is not None and hasattr(ttnn, "BufferType"): + return bt == ttnn.BufferType.DRAM + return mc == ttnn.DRAM_MEMORY_CONFIG + + +def _memory_config(spec: Any): + """``"dram"`` / ``"l1"`` / None / a ttnn.MemoryConfig -> a memory config (or None).""" + import ttnn + + if spec is None: + return None + if isinstance(spec, str): + key = spec.lower() + if key == "dram": + return ttnn.DRAM_MEMORY_CONFIG + if key == "l1": + return ttnn.L1_MEMORY_CONFIG + raise ValueError(f"memory config {spec!r}: expected 'dram', 'l1', None or a ttnn.MemoryConfig") + return spec + + +def _layout(spec: Any): + import ttnn + + if isinstance(spec, str): + key = spec.lower().replace("_layout", "") + if key == "tile": + return ttnn.TILE_LAYOUT + if key in ("row_major", "rm"): + return ttnn.ROW_MAJOR_LAYOUT + raise ValueError(f"layout {spec!r}: expected 'tile' or 'row_major'") + return spec + + +def _layout_name(spec: Any) -> str: + """``"tile"`` / ``"row_major"`` of a layout spec (string or ttnn layout), without importing ttnn for strings.""" + if isinstance(spec, str): + key = spec.lower().replace("_layout", "") + return "row_major" if key in ("row_major", "rm") else key + return "tile" if "TILE" in str(spec).upper() else "row_major" + + +def _as_float32(a: Any, what: str) -> np.ndarray: + if hasattr(a, "detach"): + a = a.detach().cpu().float().numpy() + arr = np.asarray(a, dtype=np.float32) + if not np.all(np.isfinite(arr)): + raise ValueError(f"{what} holds non-finite values") + return np.ascontiguousarray(arr) + + +def _host_tensor(a: np.ndarray, dtype: str = "bfloat16"): + """A ROW_MAJOR ttnn *host* tensor (no device involved: only TILE host tensors open the device, probe G4-X). + The data are copied (ONNX initializers are read-only arrays, which torch warns about).""" + import torch + import ttnn + + return ttnn.from_torch(torch.from_numpy(np.array(a, dtype=np.float32, copy=True)), dtype=ttnn_dtype(dtype), + layout=ttnn.ROW_MAJOR_LAYOUT) + + +# --------------------------------------------------------------------------------------------- feature maps + +@dataclass(frozen=True) +class FeatureMap: + """A device feature map: ``tensor`` holds N*H*W rows of C channels (ttnn's flattened ``[1, 1, N*H*W, C]``, + TILE or ROW_MAJOR; a ``[N, H, W, C]`` ROW_MAJOR tensor is accepted too), plus the logical sizes ttnn's layout + does not keep.""" + + tensor: Any + batch: int + height: int + width: int + channels: int + + @property + def rows(self) -> int: + return self.batch * self.height * self.width + + @property + def hw(self) -> Tuple[int, int]: + return self.height, self.width + + def with_tensor(self, tensor: Any, channels: Optional[int] = None) -> "FeatureMap": + """The same spatial map with another tensor (and channel count).""" + return FeatureMap(tensor, self.batch, self.height, self.width, + self.channels if channels is None else int(channels)) + + def deallocate(self) -> None: + """Free the tensor's device memory (``force=False``: a view's base is left to its owner, probe P2).""" + import ttnn + + if self.tensor is not None and self.tensor.is_allocated(): + ttnn.deallocate(self.tensor, False) + + +def fmap_from_numpy(nchw: Any, device: Any, *, dtype: Any = "bfloat16", layout: Any = "tile", + memory_config: Any = "dram") -> FeatureMap: + """Upload an NCHW array as a device feature map ``[1, 1, N*H*W, C]`` (TILE by default). A TILE host tensor + touches the device: run under ``bin/devrun`` (probe G4-X).""" + import torch + import ttnn + + a = _as_float32(nchw, "feature map") if np.asarray(nchw).dtype != np.uint8 else np.asarray(nchw) + if a.ndim != 4: + raise ValueError(f"expected NCHW, got shape {a.shape}") + n, c, h, w = a.shape + flat = np.ascontiguousarray(a.transpose(0, 2, 3, 1).reshape(1, 1, n * h * w, c)) + t = ttnn.from_torch(torch.from_numpy(flat), dtype=ttnn_dtype(dtype), layout=_layout(layout), device=device, + memory_config=_memory_config(memory_config)) + return FeatureMap(t, n, h, w, c) + + +def fmap_to_numpy(fm: FeatureMap, dtype: Any = np.float32) -> np.ndarray: + """Read a device feature map back as an NCHW numpy array (blocking; never inside a capture).""" + import ttnn + + a = ttnn.to_torch(fm.tensor) + a = a.float().numpy() if a.is_floating_point() else a.numpy() + a = a.reshape(-1, a.shape[-1])[: fm.rows, : fm.channels] + return np.ascontiguousarray(a.reshape(fm.batch, fm.height, fm.width, fm.channels).transpose(0, 3, 1, 2), + dtype=dtype) + + +# ------------------------------------------------------------------------------------------------- Conv2d + +class Conv2d: + """``ttnn.conv2d`` with weights prepared by the first call and reused afterwards (see the module docstring). + + Args: + weight: float array ``[Cout, Cin / groups, kh, kw]`` (OIHW, numpy or torch; BN already folded). + bias: float array ``[Cout]`` or None. + stride, dilation: int or pair. ``padding``: ``"same"`` (default), int, pair or (top, bottom, left, right). + groups: 1 for dense convs; ``groups == Cin`` is a depthwise conv (correct but expanded to dense weights by + ttnn: P5, 311 MiB for SceneSeg). + activation: None or one of :data:`FUSED_ACTIVATIONS` (fused in the epilogue). + precision: a :class:`..precision.Precision` or its spec (default :data:`CONV_PRECISION` = HiFi4 + fp32 + accumulation + packer L1 accumulation; ``Precision.weights`` is the device weight dtype: bf16 or bfp8). + output_dtype: dtype of the output (``"bfloat16"``; ``"float32"`` for logits that feed thresholds). + output_layout: ``"tile"`` (default) or ``"row_major"``. + slicing: ``"auto"`` (ttnn's rule: DRAM input -> automatic DRAM slicing, L1 input -> L1 path), ``"l1"`` + (``Conv2dL1FullSliceConfig``: the op moves the whole input to L1) or ``("height" | "width", n)`` + (explicit DRAM slices; P14 found most explicit counts rejected or slower: diagnostics only). + output_memory_config: where an L1-path output (1x1 matmul convs, L1 inputs) is placed: ``"dram"`` + (default), ``"l1"``, None (the op's sharded output) or a ttnn.MemoryConfig. DRAM-sliced convs always + write DRAM interleaved; ``"l1"`` then adds a move. + conv_config: extra ``ttnn.Conv2dConfig`` fields (``act_block_h_override``, ``shard_layout``, + ``enable_act_double_buffer``, ``deallocate_activation``, ...): optimization knobs. + weight_terms: 1 (default) or 2. With 2 the weight and the bias are split into two bf16 terms + (``hi = bf16(w)``, ``lo = bf16(w - hi)``: about 16 significant bits) run as two convs into float32 + outputs, summed in fp32 with the activation fused into the add, then cast to ``output_dtype``: the conv + then carries ~fp32 weights and bias for twice the MACs and 3 more programs. The device's own float32 + weight path is no substitute (1.5x less error than bf16, vs 3.5x for the split; YOLOX port, + logs/yolox/m3_weight_precision_probe.log). Use it where the bf16 rounding of weights and biases, which + does not average out over a deep network (a per-channel bias error is the same at every pixel), + decides an output: YOLOX's 16-class mask on public frames (97.5 % -> 99.3 % agreement in emulation). + name: label for messages and :meth:`describe`. + """ + + def __init__(self, weight: Any, bias: Any = None, *, stride: Any = 1, padding: Any = "same", + dilation: Any = 1, groups: int = 1, activation: Any = None, precision: Any = CONV_PRECISION, + output_dtype: Any = "bfloat16", output_layout: Any = "tile", slicing: Any = "auto", + output_memory_config: Any = "dram", conv_config: Optional[Dict[str, Any]] = None, + weight_terms: int = 1, name: str = "conv"): + w = _as_float32(weight, f"{name}: weight") + if w.ndim != 4: + raise ValueError(f"{name}: weight must be [Cout, Cin/groups, kh, kw], got {w.shape}") + self.name = name + self.groups = int(groups) + self.out_channels, cin_g, kh, kw = (int(s) for s in w.shape) + self.in_channels = cin_g * self.groups + if self.groups < 1 or self.out_channels % self.groups: + raise ValueError(f"{name}: groups={groups} does not divide Cout={self.out_channels}") + self.kernel = (kh, kw) + self.stride = _pair(stride, "stride") + self.dilation = _pair(dilation, "dilation") + self.padding = conv_padding(self.kernel, padding, self.dilation) + self.activation = normalize_activation(activation) + self.precision = Precision.parse(precision) + self.output_dtype = dtype_name(output_dtype) + self.output_layout = output_layout + if not (slicing == "auto" or slicing == "l1" or (isinstance(slicing, (tuple, list)) and len(slicing) == 2 + and slicing[0] in ("height", "width"))): + raise ValueError(f"{name}: slicing {slicing!r}: expected 'auto', 'l1' or ('height' | 'width', n)") + self.slicing = slicing if isinstance(slicing, str) else (str(slicing[0]), int(slicing[1])) + self.output_memory_config = output_memory_config + self.conv_config_overrides = dict(conv_config or {}) + if "activation" in self.conv_config_overrides or "weights_dtype" in self.conv_config_overrides: + raise ValueError(f"{name}: pass activation / weights dtype as arguments, not in conv_config") + b = np.zeros(self.out_channels, np.float32) if bias is None else _as_float32(bias, f"{name}: bias") + if b.shape != (self.out_channels,): + raise ValueError(f"{name}: bias must have shape ({self.out_channels},), got {b.shape}") + if int(weight_terms) not in (1, 2): + raise ValueError(f"{name}: weight_terms must be 1 or 2, got {weight_terms!r}") + self.weight_terms = int(weight_terms) + if self.weight_terms == 2 and str(_layout_name(output_layout)) != "tile": + raise ValueError(f"{name}: weight_terms=2 writes TILE outputs (the fp32 sum is cast in TILE)") + self._weight = w + self._bias = b + self._host: Optional[List[Tuple[Any, Any]]] = None + self._prepared: Dict[Tuple, Tuple[Any, Any]] = {} + + # ---- geometry + @property + def is_matmul(self) -> bool: + """1x1, stride 1, no padding, no dilation, dense: ttnn runs it as a matmul on the L1 path.""" + return (self.kernel == (1, 1) and self.stride == (1, 1) and self.padding == (0, 0, 0, 0) + and self.dilation == (1, 1) and self.groups == 1) + + def out_hw(self, height: int, width: int) -> Tuple[int, int]: + return conv_out_hw((height, width), self.kernel, self.stride, self.padding, self.dilation) + + @property + def weight(self) -> np.ndarray: + """The float32 host weight (OIHW).""" + return self._weight + + @property + def bias(self) -> np.ndarray: + return self._bias + + # ---- ttnn arguments + def host_terms(self) -> List[Tuple[np.ndarray, np.ndarray]]: + """The float32 (weight, bias) of each term: one term, or ``hi = bf16(x)`` and ``lo = bf16(x - hi)`` (both + exactly representable in bf16, so the bf16 upload is exact).""" + if self.weight_terms == 1: + return [(self._weight, self._bias)] + hi_w, hi_b = round_to_bf16(self._weight), round_to_bf16(self._bias) + return [(hi_w, hi_b), (round_to_bf16(self._weight - hi_w), round_to_bf16(self._bias - hi_b))] + + def _host_tensors(self, term: int = 0) -> Tuple[Any, Any]: + if self._host is None: + # host tensors in the device weight dtype's host precision: bf16 for bf16 / bfp8 weights (ttnn rounds + # to bfp8 itself), float32 for float32 weights (a bf16 host tensor would round them first) + host_dtype = "float32" if self.precision.weights == "float32" else "bfloat16" + self._host = [(_host_tensor(w, host_dtype), _host_tensor(b.reshape(1, 1, 1, -1), host_dtype)) + for w, b in self.host_terms()] + return self._host[term] + + def _conv_config(self, fused: bool = True): + import ttnn + + kw = dict(self.conv_config_overrides) + kw["weights_dtype"] = ttnn_dtype(self.precision.weights) + kw["activation"] = unary_with_param(self.activation) if fused else None + kw.setdefault("output_layout", _layout(self.output_layout)) + return ttnn.Conv2dConfig(**kw) + + def _slice_config(self): + import ttnn + + if self.slicing == "auto": + return None + if self.slicing == "l1": + return ttnn.Conv2dL1FullSliceConfig + kind, num = self.slicing + slice_type = ttnn.Conv2dDRAMSliceHeight if kind == "height" else ttnn.Conv2dDRAMSliceWidth + return ttnn.Conv2dSliceConfig(slice_type=slice_type, num_slices=num) + + def _spec_key(self, fm: FeatureMap) -> Tuple: + t = fm.tensor + return (fm.batch, fm.height, fm.width, str(t.dtype), str(t.layout), str(t.memory_config()), + tuple(int(s) for s in t.shape)) + + def takes_l1_path(self, x: Any) -> bool: + """Whether a call on ``x`` (a device tensor) runs ttnn's L1 path (else the DRAM-sliced path).""" + if self.slicing == "l1" or self.is_matmul: + return True + return self.slicing == "auto" and not is_dram(x) + + def __call__(self, x: Union[FeatureMap, Any], *, batch: Optional[int] = None, height: Optional[int] = None, + width: Optional[int] = None) -> FeatureMap: + """Run the conv on a :class:`FeatureMap` (or a raw device tensor plus ``batch`` / ``height`` / ``width``) + and return the output :class:`FeatureMap` (``[1, 1, N*OH*OW, Cout]``).""" + import ttnn + + fm = x if isinstance(x, FeatureMap) else FeatureMap(x, int(batch), int(height), int(width), self.in_channels) + if fm.channels != self.in_channels: + raise ValueError(f"{self.name}: input has {fm.channels} channels, the conv takes {self.in_channels}") + key = self._spec_key(fm) + l1_path = self.takes_l1_path(fm.tensor) + out_mc = _memory_config(self.output_memory_config) + split = self.weight_terms == 2 + outs = [] + for term in range(self.weight_terms): + tkey = key + (term,) + weight, bias = self._prepared.get(tkey) or self._host_tensors(term) + out, (oh, ow), (weight, bias) = ttnn.conv2d( + input_tensor=fm.tensor, weight_tensor=weight, device=fm.tensor.device(), + in_channels=self.in_channels, out_channels=self.out_channels, batch_size=fm.batch, + input_height=fm.height, input_width=fm.width, kernel_size=self.kernel, stride=self.stride, + padding=self.padding, dilation=self.dilation, groups=self.groups, bias_tensor=bias, + conv_config=self._conv_config(fused=not split), compute_config=self.precision.compute_kernel_config(), + slice_config=self._slice_config(), memory_config=out_mc if l1_path else None, + dtype=ttnn.float32 if split else ttnn_dtype(self.output_dtype), return_output_dim=True, + return_weights_and_bias=True) + self._prepared[tkey] = (weight, bias) + outs.append(out) + if (int(oh), int(ow)) != self.out_hw(fm.height, fm.width): + raise RuntimeError(f"{self.name}: ttnn returned a {oh}x{ow} output, expected " + f"{self.out_hw(fm.height, fm.width)}") + out = outs[0] + if split: + fuse = self.activation in BINARY_FUSED_ACTIVATIONS + out = ttnn.add(outs[0], outs[1], activations=[unary_with_param(self.activation)] if fuse else []) + for t in outs: + ttnn.deallocate(t, False) + if not fuse: + out = apply_activation(out, self.activation) + if self.output_dtype != "float32": + out = ttnn.typecast(out, ttnn_dtype(self.output_dtype)) + if not l1_path and out_mc is not None and not is_dram(out_mc): + out = ttnn.to_memory_config(out, out_mc) + return FeatureMap(out, fm.batch, int(oh), int(ow), self.out_channels) + + @property + def prepared_specs(self) -> int: + """Number of input specs this layer holds prepared device weights for.""" + return len({k[:-1] for k in self._prepared}) + + def release(self) -> None: + """Free the prepared device weights (the host weights stay; the next call prepares them again).""" + import ttnn + + for w, b in self._prepared.values(): + for t in (w, b): + if t is not None and t.is_allocated(): + ttnn.deallocate(t) + self._prepared.clear() + + def describe(self) -> Dict[str, Any]: + return {"name": self.name, "cin": self.in_channels, "cout": self.out_channels, "kernel": list(self.kernel), + "stride": list(self.stride), "padding": list(self.padding), "dilation": list(self.dilation), + "groups": self.groups, "activation": self.activation, "precision": self.precision.label, + "output_dtype": self.output_dtype, "slicing": self.slicing if isinstance(self.slicing, str) + else list(self.slicing), "matmul": self.is_matmul, "weight_terms": self.weight_terms} + + +# ----------------------------------------------------------------------------------- K-split (concat-free) + +def split_k_weights(weight: Any, parts: Sequence[int]) -> List[np.ndarray]: + """Split a conv weight ``[Cout, sum(parts), kh, kw]`` along its input channels: ``conv(concat(x_i), W) == + sum_i conv(x_i, W_i)``.""" + w = _as_float32(weight, "weight") + if w.ndim != 4 or w.shape[1] != sum(int(p) for p in parts): + raise ValueError(f"weight {w.shape} does not have sum(parts) = {sum(parts)} input channels") + out, start = [], 0 + for p in parts: + out.append(np.ascontiguousarray(w[:, start:start + int(p)])) + start += int(p) + return out + + +class KSplitConv: + """``conv(concat([x_1, ..., x_n], channels))`` computed as ``sum_i conv_i(x_i)`` without building the concat + (S:centerpoint:448; P14: CenterPoint's shared conv 3.6 vs 14.8 ms and PCC 0.999992 vs 0.999961). + + The bias rides on the first partial conv, the partial sums are added in order, and the activation is fused into + the last add (RELU / RELU6, P5) or applied after it. ``accumulate_dtype="float32"`` keeps the partial outputs and + their sums in fp32 and casts to ``output_dtype`` once (more accurate, more traffic); the default ``"bfloat16"`` + rounds each partial (what P14 measured). Every keyword except ``activation`` / ``output_dtype`` / + ``accumulate_dtype`` goes to the partial :class:`Conv2d` layers.""" + + def __init__(self, weight: Any, bias: Any, parts: Sequence[int], *, activation: Any = None, + output_dtype: Any = "bfloat16", accumulate_dtype: Any = "bfloat16", name: str = "ksplit", + **conv_kwargs: Any): + if len(parts) < 2: + raise ValueError(f"{name}: a K-split needs at least two parts") + self.name = name + self.parts = tuple(int(p) for p in parts) + self.activation = normalize_activation(activation) + self.output_dtype = dtype_name(output_dtype) + self.accumulate_dtype = dtype_name(accumulate_dtype) + weights = split_k_weights(weight, self.parts) + cout = weights[0].shape[0] + b = np.zeros(cout, np.float32) if bias is None else _as_float32(bias, f"{name}: bias") + self.convs = [Conv2d(w, b if i == 0 else None, activation=None, output_dtype=self.accumulate_dtype, + name=f"{name}.{i}", **conv_kwargs) for i, w in enumerate(weights)] + self.out_channels = cout + + def __call__(self, inputs: Sequence[FeatureMap]) -> FeatureMap: + import ttnn + + if len(inputs) != len(self.convs): + raise ValueError(f"{self.name}: expected {len(self.convs)} inputs, got {len(inputs)}") + total: Optional[FeatureMap] = None + n = len(inputs) + for i, (conv, x) in enumerate(zip(self.convs, inputs)): + part = conv(x) + if total is None: + total = part + continue + last = i == n - 1 + fuse = last and self.activation in BINARY_FUSED_ACTIVATIONS + acts = [unary_with_param(self.activation)] if fuse else [] + summed = ttnn.add(total.tensor, part.tensor, activations=acts) + for t in (total, part): + t.deallocate() + total = total.with_tensor(summed) + if last and not fuse: + total = total.with_tensor(apply_activation(total.tensor, self.activation)) + assert total is not None + if self.accumulate_dtype != self.output_dtype: + total = total.with_tensor(ttnn.typecast(total.tensor, ttnn_dtype(self.output_dtype))) + return total + + def release(self) -> None: + for c in self.convs: + c.release() + + def describe(self) -> Dict[str, Any]: + return {"name": self.name, "parts": list(self.parts), "activation": self.activation, + "accumulate_dtype": self.accumulate_dtype, "convs": [c.describe() for c in self.convs]} + + +# ----------------------------------------------------------------------------------- sibling merge / glue + +def merge_sibling_convs(weights: Sequence[Any], biases: Sequence[Any]) -> Tuple[np.ndarray, np.ndarray, List[int]]: + """One conv for sibling convs reading the same input (S:centerpoint:450; S:yolox section 8.5 #1): output + channels concatenated in order -> ``(weight, bias, out_channels_per_sibling)``; split the output with + :func:`split_channels`. Exact (each output channel keeps its own weights).""" + ws = [_as_float32(w, "weight") for w in weights] + bs = [np.zeros(w.shape[0], np.float32) if b is None else _as_float32(b, "bias") for w, b in zip(ws, biases)] + shapes = {w.shape[1:] for w in ws} + if len(shapes) != 1: + raise ValueError(f"sibling convs must share Cin and kernel, got {[w.shape for w in ws]}") + return (np.ascontiguousarray(np.concatenate(ws, axis=0)), np.ascontiguousarray(np.concatenate(bs)), + [int(w.shape[0]) for w in ws]) + + +def concat_channels(maps: Sequence[FeatureMap], *, memory_config: Any = "dram") -> FeatureMap: + """Concatenate feature maps of one spatial size along channels (``ttnn.concat(dim=3)``); every input must have + the same layout and dtype. TILE inputs with channel counts that are multiples of 32 avoid any re-tiling.""" + import ttnn + + if not maps: + raise ValueError("concat_channels needs at least one map") + first = maps[0] + for m in maps[1:]: + if (m.batch, m.height, m.width) != (first.batch, first.height, first.width): + raise ValueError(f"concat of maps of different sizes: {[(m.batch, m.height, m.width) for m in maps]}") + if len(maps) == 1: + return first + t = ttnn.concat([m.tensor for m in maps], dim=3, memory_config=_memory_config(memory_config)) + return first.with_tensor(t, sum(m.channels for m in maps)) + + +def split_channels(fm: FeatureMap, sizes: Sequence[int]) -> List[FeatureMap]: + """Slice a map's channels into consecutive groups of ``sizes`` (``ttnn.slice`` on the last dim).""" + import ttnn + + if sum(int(s) for s in sizes) != fm.channels: + raise ValueError(f"split sizes {list(sizes)} do not add up to {fm.channels} channels") + shape = [int(s) for s in fm.tensor.shape] + out, start = [], 0 + for s in sizes: + begin = [0] * len(shape) + end = list(shape) + begin[-1], end[-1] = start, start + int(s) + out.append(fm.with_tensor(ttnn.slice(fm.tensor, begin, end), int(s))) + start += int(s) + return out + + +def residual_add(a: FeatureMap, b: FeatureMap, activation: Any = None) -> FeatureMap: + """``a + b`` (same spec), with RELU / RELU6 fused into the add (P5: the clip6 residual of YOLOX) or another + activation applied after it.""" + import ttnn + + if (a.rows, a.channels) != (b.rows, b.channels): + raise ValueError(f"residual add of {a.rows}x{a.channels} and {b.rows}x{b.channels}") + act = normalize_activation(activation) + if act in BINARY_FUSED_ACTIVATIONS: + return a.with_tensor(ttnn.add(a.tensor, b.tensor, activations=[unary_with_param(act)])) + return a.with_tensor(apply_activation(ttnn.add(a.tensor, b.tensor), act)) + + +# ----------------------------------------------------------------------------- ConvTranspose (kernel == stride) + +class ConvTranspose2d: + """ConvTranspose2d with kernel == stride and no padding (the BEV deblocks of CenterPoint / PointPainting / + TransFusion and SceneSeg's up-sampling layers), weights prepared by the first call. + + ``method="auto"`` follows probe P5: k = 2 -> ``ttnn.conv_transpose2d`` (CP deblock1 0.64 ms vs 2.08 ms for the + rewrite), k >= 3 -> ``"linear_d2s"`` = ``ttnn.linear(Cin -> k*k*Cout)`` with the bias and activation fused, then + depth-to-space (``to_layout(ROW_MAJOR)``, ``reshape [N*h, w, k, k, C]``, ``permute (0, 2, 1, 3, 4)``, ``reshape``; + CP deblock2 k = 4: 1.97 vs 10.27 ms). The linear output channel order is (i, j, c): + ``W2[cin, (i*k + j)*Cout + c] = W[cin, c, i, j]``. Output: a ROW_MAJOR ``[1, 1, N*h*k*w*k, Cout]`` map for + ``linear_d2s`` (``output_layout="tile"`` re-tiles it), the conv's TILE output for ``conv_transpose2d``. + + ``weight``: ``[Cin, Cout, k, k]`` (torch ConvTranspose2d layout); ``bias``: ``[Cout]`` or None.""" + + METHODS = ("auto", "conv_transpose2d", "linear_d2s") + + def __init__(self, weight: Any, bias: Any = None, *, stride: Optional[int] = None, activation: Any = None, + precision: Any = CONV_PRECISION, output_dtype: Any = "bfloat16", method: str = "auto", + output_layout: Any = "tile", memory_config: Any = "dram", name: str = "deconv"): + w = _as_float32(weight, f"{name}: weight") + if w.ndim != 4 or w.shape[2] != w.shape[3]: + raise ValueError(f"{name}: weight must be [Cin, Cout, k, k], got {w.shape}") + self.name = name + self.in_channels, self.out_channels, self.k = int(w.shape[0]), int(w.shape[1]), int(w.shape[2]) + if stride is not None and int(stride) != self.k: + raise ValueError(f"{name}: only kernel == stride is supported (k={self.k}, stride={stride})") + if method not in self.METHODS: + raise ValueError(f"{name}: method {method!r}: expected one of {self.METHODS}") + self.method = ("conv_transpose2d" if self.k == 2 else "linear_d2s") if method == "auto" else method + self.activation = normalize_activation(activation) + self.precision = Precision.parse(precision) + self.output_dtype = dtype_name(output_dtype) + self.output_layout = output_layout + self.memory_config = memory_config + b = np.zeros(self.out_channels, np.float32) if bias is None else _as_float32(bias, f"{name}: bias") + if b.shape != (self.out_channels,): + raise ValueError(f"{name}: bias must have shape ({self.out_channels},), got {b.shape}") + self._weight, self._bias = w, b + self._prepared: Dict[Tuple, Tuple[Any, Any]] = {} + self._linear: Optional[Tuple[Any, Any]] = None + + def _spec_key(self, fm: FeatureMap) -> Tuple: + t = fm.tensor + return (fm.batch, fm.height, fm.width, str(t.dtype), str(t.layout), str(t.memory_config())) + + def linear_weights(self) -> Tuple[np.ndarray, np.ndarray]: + """Host form of the ``linear_d2s`` weights: ``W2 [Cin, k*k*Cout]`` in (i, j, c) order, bias repeated.""" + k = self.k + w2 = self._weight.transpose(0, 2, 3, 1).reshape(self.in_channels, k * k * self.out_channels) + return np.ascontiguousarray(w2), np.ascontiguousarray(np.tile(self._bias, k * k)) + + def __call__(self, x: FeatureMap) -> FeatureMap: + import ttnn + + if x.channels != self.in_channels: + raise ValueError(f"{self.name}: input has {x.channels} channels, the layer takes {self.in_channels}") + k = self.k + if self.method == "conv_transpose2d": + key = self._spec_key(x) + # float32 host tensors for float32 weights, as Conv2d (a bf16 host tensor would round them first) + host_dtype = "float32" if self.precision.weights == "float32" else "bfloat16" + weight, bias = self._prepared.get(key) or (_host_tensor(self._weight, host_dtype), + _host_tensor(self._bias.reshape(1, 1, 1, -1), host_dtype)) + conv_config = ttnn.Conv2dConfig(weights_dtype=ttnn_dtype(self.precision.weights), + activation=unary_with_param(self.activation), + output_layout=_layout(self.output_layout)) + out, (weight, bias) = ttnn.conv_transpose2d( + input_tensor=x.tensor, weight_tensor=weight, device=x.tensor.device(), + in_channels=self.in_channels, out_channels=self.out_channels, batch_size=x.batch, + input_height=x.height, input_width=x.width, kernel_size=(k, k), stride=(k, k), padding=(0, 0), + output_padding=(0, 0), dilation=(1, 1), groups=1, bias_tensor=bias, conv_config=conv_config, + compute_config=self.precision.compute_kernel_config(), dtype=ttnn_dtype(self.output_dtype), + mirror_kernel=True, return_weights_and_bias=True) + self._prepared[key] = (weight, bias) + return FeatureMap(out, x.batch, x.height * k, x.width * k, self.out_channels) + # linear + depth-to-space + import torch + + device = x.tensor.device() + if self._linear is None: + w2, b2 = self.linear_weights() + wdt = ttnn_dtype(self.precision.weights) + self._linear = ( + ttnn.from_torch(torch.from_numpy(w2), dtype=wdt, layout=ttnn.TILE_LAYOUT, device=device), + ttnn.from_torch(torch.from_numpy(b2.reshape(1, -1)), dtype=wdt, layout=ttnn.TILE_LAYOUT, + device=device)) + weight, bias = self._linear + t = x.tensor if x.tensor.layout == ttnn.TILE_LAYOUT else ttnn.to_layout(x.tensor, ttnn.TILE_LAYOUT) + y = ttnn.linear(t, weight, bias=bias, activation=unary_with_param(self.activation), + compute_kernel_config=self.precision.compute_kernel_config(), + memory_config=_memory_config(self.memory_config), dtype=ttnn_dtype(self.output_dtype)) + y_rm = ttnn.to_layout(y, ttnn.ROW_MAJOR_LAYOUT) + ttnn.deallocate(y, False) + c = self.out_channels + y5 = ttnn.reshape(y_rm, (x.batch * x.height, x.width, k, k, c)) + y5 = ttnn.permute(y5, (0, 2, 1, 3, 4)) + out = ttnn.reshape(y5, (1, 1, x.batch * x.height * k * x.width * k, c)) + if _layout(self.output_layout) == ttnn.TILE_LAYOUT: + out = ttnn.to_layout(out, ttnn.TILE_LAYOUT) + return FeatureMap(out, x.batch, x.height * k, x.width * k, c) + + def release(self) -> None: + import ttnn + + tensors = [t for pair in self._prepared.values() for t in pair] + list(self._linear or ()) + for t in tensors: + if t is not None and t.is_allocated(): + ttnn.deallocate(t) + self._prepared.clear() + self._linear = None + + def describe(self) -> Dict[str, Any]: + return {"name": self.name, "cin": self.in_channels, "cout": self.out_channels, "k": self.k, + "method": self.method, "activation": self.activation, "precision": self.precision.label, + "output_dtype": self.output_dtype} diff --git a/code/tt_depthpro2/ttaw/ops/deform.py b/code/tt_depthpro2/ttaw/ops/deform.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd110e51e6c380f500c86e381b93364e94ae3e4 --- /dev/null +++ b/code/tt_depthpro2/ttaw/ops/deform.py @@ -0,0 +1,182 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C23: ``ttnn.grid_sample`` helpers (PLAN.md section 1.2 row C23; probe P9, common/PROBES.md; first built by the +BEVDet port for AlignBEV and FPN_LSS). + +Rules from probe P9 (``common/probes/g4-attention-gridsample-msda.md``), enforced or encoded here: + +- **fp32 grids** for every data-dependent grid (bf16 grids cost PCC 0.9988 at 53 px and 0.992 at 128 px); +- **input C % 32 == 0** (C = 80 is rejected; zero pad channels stay exactly 0): :func:`padded_channels`, + :func:`pad_channels`; +- **per-batch grids**: grid N must equal input N (no broadcast over the batch); +- **ROW_MAJOR, interleaved (or height-sharded)** input and grid, ``padding_mode="zeros"`` only; +- **never a FLOAT32 input together with ``fp32_dest_acc_en``**: wrong, non-deterministic output (strict xfail in P9); + :func:`grid_sample` refuses it; +- **exact integer coordinates**: the kernel recovers pixel coordinates as ``x = g * W/2 + (W - 1)/2`` in fp32 + (``grid_sample_reader_common.hpp``, align_corners=False), so the align_corners=False normalisation + ``g = (2x + 1) / W - 1`` returns integer x exactly whenever ``(2x + 1) / W`` is exact in fp32 (``W`` a power of + two): an identity warp is then a bit-exact copy (P9: the literal align_corners=True normalisation leaves 2.8-7.6 % + of values off by up to 1/32). Zero padding acts in pixel space, so the normalisation choice does not change what + is sampled: callers state pixel coordinates (:func:`affine_grid`, :func:`resize_grid`) and always call the op with + ``align_corners=False``; +- the four bilinear weights are computed in fp32 and **truncated** (not rounded) to bf16 by the kernel: a 0.33-0.6 % + rrmse floor for fractional coordinates (plan risk R3; K5 with fp32 weights removes it). :func:`emulate_grid_sample` + reproduces that arithmetic on the host (the device test's oracle). + +Host functions are numpy only (grids are built on the host, per frame or once, and uploaded as fp32 ROW_MAJOR +tensors); :func:`grid_sample` is the device call with the checks above. DCNv2 as one grid_sample with K = 9 +(``batch_output_channels=True``, BEVFormer / METEOR) and the fused MSDA wrapper are added by their ports. +""" +from __future__ import annotations + +from typing import Any, Optional, Sequence, Tuple + +import numpy as np + +__all__ = ["OUTSIDE", "padded_channels", "pad_channels", "pixel_to_grid", "kernel_pixels", "affine_pixel_coords", + "affine_grid", "resize_pixel_coords", "resize_grid", "emulate_grid_sample", "grid_sample"] + +F32 = np.float32 +# A normalised coordinate whose four taps fall outside any input (pixel -1.5 W - 0.5): the sample is exactly 0. +OUTSIDE = F32(-4.0) + + +def padded_channels(c: int, multiple: int = 32) -> int: + """The channel count ``grid_sample`` accepts for ``c`` real channels (the next multiple of 32).""" + return -(-int(c) // int(multiple)) * int(multiple) + + +def pad_channels(x: np.ndarray, multiple: int = 32) -> np.ndarray: + """Zero-pad the last (channel) dimension of an NHWC array to a multiple of ``multiple`` (no copy when aligned).""" + x = np.asarray(x) + c = x.shape[-1] + cp = padded_channels(c, multiple) + if cp == c: + return x + out = np.zeros(x.shape[:-1] + (cp,), x.dtype) + out[..., :c] = x + return out + + +def pixel_to_grid(px: Any, size: int) -> np.ndarray: + """Pixel coordinate (0 = centre of the first pixel) -> normalised coordinate for ``align_corners=False``: + ``(2 px + 1) / size - 1`` in float32 (exact for integer ``px`` when ``size`` is a power of two).""" + p = np.asarray(px, F32) + return (F32(2.0) * p + F32(1.0)) / F32(size) - F32(1.0) + + +def kernel_pixels(g: Any, size: int) -> np.ndarray: + """The pixel coordinate the device kernel recovers from a normalised coordinate (align_corners=False): + ``g * size/2 + (size - 1)/2`` in float32.""" + g = np.asarray(g, F32) + return g * F32(size / 2.0) + F32((size - 1) / 2.0) + + +def affine_pixel_coords(transforms: np.ndarray, out_hw: Tuple[int, int]) -> Tuple[np.ndarray, np.ndarray]: + """Per batch n and output pixel (h, w): ``ix = a w + b h + c``, ``iy = d w + e h + f`` in float32 with one + rounding per operation (``transforms`` [N, 6] = (a, b, c, d, e, f), the BEVDet AlignBEV / BEVFormer-style pixel + affine) -> (ix, iy) [N, H, W].""" + t = np.asarray(transforms, F32).reshape(-1, 6) + h, w = out_hw + hh, ww = np.meshgrid(np.arange(h, dtype=F32), np.arange(w, dtype=F32), indexing="ij") + a, b, c, d, e, f = (t[:, k, None, None] for k in range(6)) + ix = (a * ww + b * hh) + c + iy = (d * ww + e * hh) + f + return ix.astype(F32), iy.astype(F32) + + +def affine_grid(transforms: np.ndarray, in_hw: Tuple[int, int], out_hw: Optional[Tuple[int, int]] = None, *, + valid: Optional[Sequence[bool]] = None) -> np.ndarray: + """fp32 grid [N, H, W, 2] (x, y) sampling an ``in_hw`` input at :func:`affine_pixel_coords` (align_corners=False + normalisation: identity transforms are bit-exact copies for power-of-two input sizes). Batches with + ``valid[n] == False`` sample :data:`OUTSIDE` (exact zeros, e.g. a history slot that holds no frame yet).""" + out_hw = tuple(in_hw) if out_hw is None else tuple(out_hw) + ix, iy = affine_pixel_coords(transforms, out_hw) + grid = np.stack([pixel_to_grid(ix, in_hw[1]), pixel_to_grid(iy, in_hw[0])], axis=-1).astype(F32) + if valid is not None: + v = np.asarray(valid, bool).reshape(-1) + if v.size != grid.shape[0]: + raise ValueError(f"valid has {v.size} entries for {grid.shape[0]} batches") + grid[~v] = OUTSIDE + return np.ascontiguousarray(grid) + + +def resize_pixel_coords(in_size: int, out_size: int, align_corners: bool = True) -> np.ndarray: + """Source pixel of every output pixel of a 1-D bilinear resize (float64), torch's ``F.interpolate`` rules: + align_corners=True ``i (in - 1) / (out - 1)``; False ``(i + 0.5) in / out - 0.5`` (not clamped: the zero padding + of grid_sample differs from torch's edge clamp there, so prefer C18 ``Resize2d`` for align_corners=False).""" + i = np.arange(out_size, dtype=np.float64) + if align_corners: + return i * (in_size - 1) / max(out_size - 1, 1) + return (i + 0.5) * in_size / out_size - 0.5 + + +def resize_grid(in_hw: Tuple[int, int], out_hw: Tuple[int, int], *, align_corners: bool = True, + batch: int = 1) -> np.ndarray: + """Static fp32 grid [batch, Ho, Wo, 2] of a bilinear resize (source pixels in float64, normalised with the + align_corners=False formula; call :func:`grid_sample`). For align_corners=True every source pixel lies inside + the input, so the result equals ``F.interpolate(..., align_corners=True)`` up to the bf16 weight truncation.""" + sy = resize_pixel_coords(in_hw[0], out_hw[0], align_corners) + sx = resize_pixel_coords(in_hw[1], out_hw[1], align_corners) + gx = ((2.0 * sx + 1.0) / in_hw[1] - 1.0).astype(F32) + gy = ((2.0 * sy + 1.0) / in_hw[0] - 1.0).astype(F32) + grid = np.empty((out_hw[0], out_hw[1], 2), F32) + grid[..., 0] = gx[None, :] + grid[..., 1] = gy[:, None] + return np.ascontiguousarray(np.broadcast_to(grid, (int(batch),) + grid.shape)) + + +def _truncate_bf16(a: np.ndarray) -> np.ndarray: + bits = np.ascontiguousarray(a, F32).view(np.uint32) & np.uint32(0xFFFF0000) + return bits.view(F32) + + +def emulate_grid_sample(x: np.ndarray, grid: np.ndarray) -> np.ndarray: + """Host emulation of the device's bilinear ``grid_sample`` (align_corners=False, zero padding): pixel recovery + as :func:`kernel_pixels`, ``floor``, fp32 fractions and weights truncated to bf16, taps outside the input skipped. + ``x`` [N, H, W, C], ``grid`` [N, Ho, Wo, 2] -> [N, Ho, Wo, C] float64 (the device sums the four bf16 products + in its own order, so compare with a tolerance; an exact identity / outside sample is exact on both).""" + x = np.asarray(x, np.float64) + g = np.asarray(grid, F32) + n, h, w, _ = x.shape + px = kernel_pixels(g[..., 0], w) + py = kernel_pixels(g[..., 1], h) + x0 = np.floor(px).astype(np.int64) + y0 = np.floor(py).astype(np.int64) + fx = (px - x0.astype(F32)).astype(F32) + fy = (py - y0.astype(F32)).astype(F32) + one = F32(1.0) + out = np.zeros(g.shape[:-1] + (x.shape[-1],), np.float64) + bidx = np.arange(n)[:, None, None] + for dy, wy in ((0, one - fy), (1, fy)): + for dx, wx in ((0, one - fx), (1, fx)): + yy, xx = y0 + dy, x0 + dx + ok = (yy >= 0) & (yy < h) & (xx >= 0) & (xx < w) + wgt = _truncate_bf16((wy * wx).astype(F32)).astype(np.float64) * ok + vals = x[bidx, np.clip(yy, 0, h - 1), np.clip(xx, 0, w - 1)] + out += vals * wgt[..., None] + return out + + +def grid_sample(x: Any, grid: Any, *, compute_kernel_config: Any = None, memory_config: Any = None, + batch_output_channels: bool = False): + """``ttnn.grid_sample(x, grid)``: bilinear, zero padding, ``align_corners=False`` (pair it with + :func:`pixel_to_grid` / :func:`affine_grid` / :func:`resize_grid`), with the P9 rules checked before the call. + The output goes to DRAM by default.""" + import ttnn + + if x.layout != ttnn.ROW_MAJOR_LAYOUT or grid.layout != ttnn.ROW_MAJOR_LAYOUT: + raise ValueError("grid_sample needs ROW_MAJOR input and grid") + if int(x.padded_shape[-1]) % 32: + raise ValueError(f"grid_sample input channels must be a multiple of 32, got {x.padded_shape[-1]} " + "(pad them: deform.pad_channels)") + if int(x.shape[0]) != int(grid.shape[0]): + raise ValueError(f"grid batch {grid.shape[0]} != input batch {x.shape[0]} (expand the grid per batch)") + if grid.dtype != ttnn.float32: + raise ValueError("use an fp32 grid for data-dependent sampling (probe P9: bf16 grids lose PCC)") + if x.dtype == ttnn.float32 and compute_kernel_config is not None and \ + getattr(compute_kernel_config, "fp32_dest_acc_en", False): + raise ValueError("a FLOAT32 input with fp32_dest_acc_en returns garbage (probe P9 defect)") + return ttnn.grid_sample(x, grid, mode="bilinear", padding_mode="zeros", align_corners=False, + use_precomputed_grid=False, batch_output_channels=batch_output_channels, + memory_config=ttnn.DRAM_MEMORY_CONFIG if memory_config is None else memory_config, + compute_kernel_config=compute_kernel_config) diff --git a/code/tt_depthpro2/ttaw/ops/gather.py b/code/tt_depthpro2/ttaw/ops/gather.py new file mode 100644 index 0000000000000000000000000000000000000000..6f32a6abca945e987405f2407350cc44764887b3 --- /dev/null +++ b/code/tt_depthpro2/ttaw/ops/gather.py @@ -0,0 +1,133 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C19: row gathers with ``ttnn.embedding`` and the gather form of scatter (PLAN.md section 1.2 row C19; probe P4). + +A scatter of ``P`` source rows into an ``N``-row destination (a BEV canvas, a to-dense map) is written as a +gather: the host builds ``index[n]`` = the source row of destination row ``n``, or ``sentinel`` (an explicit +all-zero row appended to the table) where nothing lands. Every shape is static, so it traces, and nothing has to +clear the destination first. Probe P4 (common/PROBES.md) measured it bit-exact at the real shapes, with: + +- the table ROW_MAJOR bf16 ``[1, 1, V, D]`` (``D % 32 == 0`` for the fused tilized output), UINT32 indices + ``[1, N]`` (ROW_MAJOR); +- **the default call** ``ttnn.embedding(index, table, layout=TILE, padding_idx=sentinel, + embeddings_type=PADDED)``: 0.19-0.54 ms per canvas (CenterPoint 480 x 480: 0.21 ms); GENERIC is 5.4-14.6x slower + on canvases (most indices hit the sentinel); +- **PADDED returns the table's own pad row, not zeros** (S:ptv3:304): the zero row must really be in the table + (:func:`with_zero_rows`). + +``ttnn.embedding`` is bf16-only; fp32 row gathers are ``ttnn.gather`` (bit-exact but ~1 us per index, probe P13), +not covered here. Indices must lie in ``[0, V)``: an out-of-range index reads outside the table (and can hang the +chip), so :func:`check_index` validates host index arrays before they are uploaded. + +numpy only at import; ttnn is imported inside the device functions. +""" +from __future__ import annotations + +from typing import Any, Optional, Tuple + +import numpy as np + +__all__ = [ + "check_index", + "gather_rows", + "gather_rows_numpy", + "scatter_rows", + "scatter_rows_numpy", + "with_zero_rows", +] + + +def check_index(index: Any, *, num_rows: int, sentinel: Optional[int] = None) -> np.ndarray: + """Validate a host gather index and return it as a contiguous ``uint32`` array of shape ``[1, N]``. + + ``num_rows`` is the number of real source rows; valid entries are ``0 <= i < num_rows`` or ``i == sentinel`` + (the zero row, conventionally ``num_rows``). Raises ``ValueError`` for anything else (negative, too large, + non-integral, non-finite), because an out-of-range index makes the device read outside the table.""" + a = np.asarray(index) + if a.dtype.kind == "f": + if not np.all(np.isfinite(a)) or np.any(a != np.floor(a)): + raise ValueError("gather index holds non-integral or non-finite values") + elif a.dtype.kind not in "iu": + raise ValueError(f"gather index must be integral, got dtype {a.dtype}") + flat = a.reshape(-1).astype(np.int64) + valid = (flat >= 0) & (flat < int(num_rows)) + if sentinel is not None: + valid |= flat == int(sentinel) + bad = ~valid + if np.any(bad): + i = int(np.flatnonzero(bad)[0]) + raise ValueError(f"gather index [{i}] = {int(flat[i])} is outside [0, {num_rows})" + + ("" if sentinel is None else f" and is not the sentinel {sentinel}")) + return np.ascontiguousarray(flat.astype(np.uint32).reshape(1, -1)) + + +def gather_rows_numpy(index: Any, table: Any) -> np.ndarray: + """Host oracle: ``out[n] = table[index[n]]`` (``table`` ``[V, D]``).""" + t = np.asarray(table) + return t.reshape(-1, t.shape[-1])[np.asarray(index).reshape(-1).astype(np.int64)] + + +def scatter_rows_numpy(rows: Any, index: Any, *, sentinel: int) -> np.ndarray: + """Host oracle of :func:`scatter_rows`: ``rows`` ``[P, D]`` with a zero row appended at ``sentinel`` + (``sentinel >= P``; rows between ``P`` and ``sentinel`` are zero too), gathered by ``index``.""" + r = np.asarray(rows, dtype=np.float32) + r = r.reshape(-1, r.shape[-1]) + table = np.zeros((max(int(sentinel) + 1, r.shape[0]), r.shape[1]), np.float32) + table[: r.shape[0]] = r + return gather_rows_numpy(index, table) + + +def _rm(t: Any): + import ttnn + + return ttnn.to_layout(t, ttnn.ROW_MAJOR_LAYOUT) if t.layout != ttnn.ROW_MAJOR_LAYOUT else t + + +def with_zero_rows(rows: Any, count: int = 1): + """A ROW_MAJOR gather table ``[1, 1, P + count, D]``: the device rows ``rows`` (``[1, 1, P, D]``, TILE or + ROW_MAJOR, bf16) followed by ``count`` zero rows (the sentinel rows of :func:`scatter_rows`). One ``ttnn.pad`` + on the device (plus an untilize for a TILE input); traceable.""" + import ttnn + + if count < 1: + raise ValueError("count must be >= 1") + shape = tuple(int(s) for s in rows.shape) + if len(shape) != 4 or shape[0] != 1 or shape[1] != 1: + raise ValueError(f"rows must be [1, 1, P, D], got {shape}") + rm = _rm(rows) + return ttnn.pad(rm, [(0, 0), (0, 0), (0, int(count)), (0, 0)], 0.0) + + +def gather_rows(index: Any, table: Any, *, sentinel: Optional[int] = None, layout: str = "tile", + memory_config: Any = None): + """``out[0, 0, n] = table[0, 0, index[0, n]]`` on the device -> ``[1, 1, N, D]``. + + ``index``: UINT32 ROW_MAJOR ``[1, N]`` device tensor; ``table``: bf16 ROW_MAJOR ``[1, 1, V, D]`` (a TILE table + is untilized by ttnn first: one extra program). ``sentinel``: the index of an all-zero table row; given, the + call is P4's fast PADDED form (the table must really hold zeros there). ``layout="tile"`` (default) writes + the tilized output directly when ``N % 32 == 0`` and ``D % 32 == 0``.""" + import ttnn + + lay = ttnn.TILE_LAYOUT if layout == "tile" else ttnn.ROW_MAJOR_LAYOUT + kw = {"layout": lay} + if sentinel is not None: + kw.update(padding_idx=int(sentinel), embeddings_type=ttnn.EmbeddingsType.PADDED) + if memory_config is not None: + kw["memory_config"] = memory_config + out = ttnn.embedding(index, table, **kw) # [1, N, D] + n, d = int(out.shape[-2]), int(out.shape[-1]) + return ttnn.reshape(out, (1, 1, n, d)) + + +def scatter_rows(rows: Any, index: Any, *, sentinel: Optional[int] = None, layout: str = "tile", + memory_config: Any = None) -> Tuple[Any, Any]: + """Gather-form scatter: ``canvas[n] = rows[index[n]]``, or zeros where ``index[n] == sentinel``. + + ``rows``: ``[1, 1, P, D]`` device rows (TILE or ROW_MAJOR bf16); ``sentinel`` defaults to ``P`` (the zero + row appended by :func:`with_zero_rows`). Returns ``(canvas, table)``: the ``[1, 1, N, D]`` canvas (TILE by + default, e.g. the NHWC input of a conv) and the table, which the caller may deallocate.""" + p = int(rows.shape[-2]) + sentinel = p if sentinel is None else int(sentinel) + if sentinel < p: + raise ValueError(f"sentinel {sentinel} must be >= the number of source rows {p}") + table = with_zero_rows(rows, sentinel - p + 1) + return gather_rows(index, table, sentinel=sentinel, layout=layout, memory_config=memory_config), table diff --git a/code/tt_depthpro2/ttaw/ops/heatmap.py b/code/tt_depthpro2/ttaw/ops/heatmap.py new file mode 100644 index 0000000000000000000000000000000000000000..c331ea000033e57e8be553c508de5b46478193f2 --- /dev/null +++ b/code/tt_depthpro2/ttaw/ops/heatmap.py @@ -0,0 +1,245 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C22: heatmap peaks of the query-based LiDAR detectors -- sigmoid and the 3x3 local maximum (PLAN.md section 1.2 +row C22; probe P6, common/PROBES.md). + +TransFusion, BEVFusion and PTv3 keep a heatmap cell only where it is the maximum of its 3x3 neighbourhood, with +model-specific border and class rules: + +- ``"transfusion"`` (TF, S:transfusion:169): ``MaxPool 3x3 s1 p0`` padded back with a ZERO border, every class: the + border cells are always suppressed; +- ``"bevfusion"`` (BF, S:bevfusion:258): classes ``pooled_classes`` (default 0-3) as TF; the other classes are not + pooled (``local_max = heat``): every cell passes; +- ``"ptv3"`` (PT, S:ptv3:217): ``local_max`` starts as the heat itself and only the interior of the pooled classes is + replaced by the pool: border cells and the other classes pass. + +All three are one exact masked chain (P6, bit-exact on the device, TF 95 / BF 85 / PT 145 us): + + keep = m_pass + (heat == max_pool2d(heat, 3x3, stride 1, padding 1)) * m_eq out = heat * keep + +with two constant masks ``m_eq`` / ``m_pass`` (disjoint, values 0 / 1, laid out as the NHWC rows ``[H*W, C]`` of the +heatmap). The pool's padding never matters: a padded window only covers border cells, where ``m_eq`` is 0. Not the +literal ``p0`` pool + pad form (222 us for TF and two more programs). ``ttnn.max_pool2d`` is bf16 only (FLOAT32 is +rejected, ``pool_op.cpp:30``), so the heat is bf16: :func:`sigmoid_heat` takes fp32 logits through an fp32 sigmoid and +rounds once. + +Device layout: the heatmap is a TILE ``[1, 1, H*W, C]`` tensor (what a conv head writes); the result has the same +layout (the input of C21's class-major top-k row and of the query-heat gather of C26). + +numpy only at import; ttnn is imported inside the device functions. +""" +from __future__ import annotations + +from typing import Any, Dict, Optional, Sequence, Tuple + +import numpy as np + +__all__ = ["RULES", "DEFAULT_POOLED_CLASSES", "local_max_masks", "local_max_numpy", "local_max_literal_numpy", + "sigmoid_heat", "sigmoid_heat_numpy", "LocalMax"] + +RULES = ("transfusion", "bevfusion", "ptv3") +DEFAULT_POOLED_CLASSES = 4 # BF / PT: classes 0-3 pooled (the last class(es) pass) + + +def _pooled(classes: int, rule: str, pooled_classes: Optional[Sequence[int]]) -> np.ndarray: + if rule not in RULES: + raise ValueError(f"rule {rule!r}: expected one of {RULES}") + if pooled_classes is None: + pooled_classes = range(classes) if rule == "transfusion" else range(min(DEFAULT_POOLED_CLASSES, classes)) + p = np.zeros(classes, np.float32) + for c in pooled_classes: + if not 0 <= int(c) < classes: + raise ValueError(f"pooled class {c} outside [0, {classes})") + p[int(c)] = 1.0 + if rule == "transfusion" and not p.all(): + raise ValueError("the transfusion rule pools every class") + return p + + +def local_max_masks(height: int, width: int, classes: int, *, rule: str = "transfusion", + pooled_classes: Optional[Sequence[int]] = None, kernel: int = 3) -> Tuple[np.ndarray, np.ndarray]: + """The constant masks ``(m_pass, m_eq)`` of the chain for ``rule`` (module docstring), float32 NHWC rows + ``[height * width, classes]``. ``kernel`` (odd): the pool size; the border is ``kernel // 2`` cells wide.""" + if kernel < 1 or kernel % 2 == 0: + raise ValueError(f"kernel must be odd and positive, got {kernel}") + r = kernel // 2 + if height <= 2 * r or width <= 2 * r: + raise ValueError(f"a {height}x{width} map has no interior for a {kernel}x{kernel} pool") + pooled = _pooled(classes, rule, pooled_classes) + interior = np.zeros((height, width, 1), np.float32) + interior[r:height - r, r:width - r] = 1.0 + m_eq = interior * pooled[None, None, :] + if rule == "transfusion": + m_pass = np.zeros_like(m_eq) + elif rule == "bevfusion": + m_pass = np.broadcast_to(1.0 - pooled[None, None, :], m_eq.shape).astype(np.float32) + else: + m_pass = 1.0 - m_eq + return (np.ascontiguousarray(m_pass.reshape(height * width, classes)), + np.ascontiguousarray(m_eq.reshape(height * width, classes))) + + +def _pool_numpy(heat_nhwc: np.ndarray, height: int, width: int, kernel: int) -> np.ndarray: + """3x3 (k x k) stride-1 max pool with ``-inf`` padding of NHWC rows ``[H*W, C]`` (exact on any float data).""" + c = heat_nhwc.shape[-1] + x = np.asarray(heat_nhwc, np.float64).reshape(height, width, c) + r = kernel // 2 + p = np.full((height + 2 * r, width + 2 * r, c), -np.inf) + p[r:r + height, r:r + width] = x + out = np.full_like(x, -np.inf) + for dy in range(kernel): + for dx in range(kernel): + np.maximum(out, p[dy:dy + height, dx:dx + width], out=out) + return out.reshape(height * width, c) + + +def local_max_numpy(heat_nhwc: Any, height: int, width: int, m_pass: Any, m_eq: Any, kernel: int = 3) -> np.ndarray: + """Host oracle of the masked chain on NHWC rows ``[H*W, C]`` (float32 out; exact on bf16-valued input).""" + h = np.asarray(heat_nhwc, np.float32).reshape(height * width, -1) + pooled = _pool_numpy(h, height, width, kernel) + keep = np.asarray(m_pass, np.float32) + (h == pooled).astype(np.float32) * np.asarray(m_eq, np.float32) + return (h * keep).astype(np.float32) + + +def local_max_literal_numpy(heat_nchw: Any, rule: str = "transfusion", *, + pooled_classes: Optional[Sequence[int]] = None, kernel: int = 3) -> np.ndarray: + """The models' literal forms (``heat * (heat == local_max)``, NCHW ``(C, H, W)`` or ``(1, C, H, W)``), the oracle + the masked chain is proven against: TF ``max_pool p0`` + zero border (all classes); BF pooled classes as TF and + the others ``local_max = heat``; PT ``local_max = heat`` with the interior of the pooled classes pooled.""" + x = np.asarray(heat_nchw, np.float32) + squeeze = x.ndim == 4 + if squeeze: + x = x[0] + c, h, w = x.shape + pooled = _pooled(c, rule, pooled_classes).astype(bool) + r = kernel // 2 + full = _pool_numpy(x.reshape(c, h * w).T, h, w, kernel).T.reshape(c, h, w) + interior = np.zeros((h, w), bool) + interior[r:h - r, r:w - r] = True + if rule == "transfusion": + local = np.where(interior[None], full, 0.0) + elif rule == "bevfusion": + local = np.where(pooled[:, None, None], np.where(interior[None], full, 0.0), x) + else: + local = np.where(pooled[:, None, None] & interior[None], full, x) + out = (x * (x == local)).astype(np.float32) + return out[None] if squeeze else out + + +def sigmoid_heat_numpy(logits: Any, dtype: str = "bfloat16") -> np.ndarray: + """Host model of :func:`sigmoid_heat`: float64 sigmoid of the float32 logits, rounded once to ``dtype`` (bf16 RNE).""" + s = (1.0 / (1.0 + np.exp(-np.asarray(logits, np.float64)))).astype(np.float32) + if dtype in ("bfloat16", "bf16"): + from ..tensors import round_to_bf16 + + return round_to_bf16(s) + return s + + +def sigmoid_heat(logits: Any, *, dtype: str = "bfloat16", memory_config: Any = None): + """Device ``sigmoid(logits)`` computed in the logits' dtype (fp32 logits: an fp32 sigmoid) and cast once to + ``dtype`` (bf16: what ``max_pool2d`` and C21's ``topk_large_indices`` take). Returns ``(heat, sig)``: the cast + heat and the sigmoid before the cast (the same tensor when no cast is needed).""" + import ttnn + + from ..tensors import ttnn_dtype + + kw = {} if memory_config is None else {"memory_config": memory_config} + sig = ttnn.sigmoid(logits, **kw) + want = ttnn_dtype(dtype) + heat = sig if sig.dtype == want else ttnn.typecast(sig, want) + return heat, sig + + +def _mc(spec: Any): + import ttnn + + if spec is None or spec == "dram": + return ttnn.DRAM_MEMORY_CONFIG + if spec == "l1": + return ttnn.L1_MEMORY_CONFIG + return spec + + +class LocalMax: + """The device chain for one heatmap geometry: ``heat`` (bf16 TILE ``[1, 1, H*W, C]``) -> ``heat * keep``. + + The masks are uploaded (bf16 TILE, exact 0 / 1) by the first call, outside any capture; with the TF rule + (``m_pass`` = 0) the chain is ``max_pool2d``, ``eq``, ``multiply`` (keep = eq * m_eq), ``multiply``; otherwise + ``addcmul(m_pass, eq, m_eq)`` replaces the first multiply. ``memory_config``: where the pool and the masks live + (``"dram"`` default; ``"l1"`` is P6's 95 us form for maps that fit).""" + + def __init__(self, height: int, width: int, classes: int, *, rule: str = "transfusion", + pooled_classes: Optional[Sequence[int]] = None, kernel: int = 3, memory_config: Any = "dram", + name: str = "local_max"): + self.height, self.width, self.classes = int(height), int(width), int(classes) + self.rule = rule + self.kernel = int(kernel) + self.name = name + self.m_pass, self.m_eq = local_max_masks(self.height, self.width, self.classes, rule=rule, + pooled_classes=pooled_classes, kernel=self.kernel) + self.passes = bool(self.m_pass.any()) + self.memory_config = memory_config + self._dev: Optional[Dict[str, Any]] = None + + @property + def cells(self) -> int: + return self.height * self.width + + def _upload(self, device: Any) -> Dict[str, Any]: + import torch + import ttnn + + def up(a: np.ndarray): + t = torch.from_numpy(np.ascontiguousarray(a.reshape(1, 1, self.cells, self.classes))) + return ttnn.from_torch(t, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device, + memory_config=_mc(self.memory_config)) + + self._dev = {"m_eq": up(self.m_eq), "m_pass": up(self.m_pass) if self.passes else None} + return self._dev + + def __call__(self, heat: Any): + import ttnn + + shape = tuple(int(s) for s in heat.shape) + if shape != (1, 1, self.cells, self.classes): + raise ValueError(f"{self.name}: heat must be [1, 1, {self.cells}, {self.classes}], got {shape}") + if heat.dtype != ttnn.bfloat16: + raise ValueError(f"{self.name}: max_pool2d takes bf16 only (got {heat.dtype}): use sigmoid_heat") + dev = self._dev or self._upload(heat.device()) + r = self.kernel // 2 + pooled = ttnn.max_pool2d(input_tensor=heat, batch_size=1, input_h=self.height, input_w=self.width, + channels=self.classes, kernel_size=[self.kernel, self.kernel], stride=[1, 1], + padding=[r, r], dilation=[1, 1], ceil_mode=False, + memory_config=_mc(self.memory_config), output_layout=ttnn.TILE_LAYOUT) + if tuple(int(s) for s in pooled.shape) != shape: + full = pooled + pooled = ttnn.slice(full, [0, 0, 0, 0], list(shape)) + ttnn.deallocate(full, False) + eq = ttnn.eq(heat, pooled) + ttnn.deallocate(pooled, False) + if self.passes: + keep = ttnn.addcmul(dev["m_pass"], eq, dev["m_eq"]) + else: + keep = ttnn.multiply(eq, dev["m_eq"]) + ttnn.deallocate(eq, False) + out = ttnn.multiply(heat, keep) + ttnn.deallocate(keep, False) + return out + + def numpy(self, heat_nhwc: Any) -> np.ndarray: + """Host oracle of this chain on NHWC rows (bf16-valued input gives the device result bit for bit).""" + return local_max_numpy(heat_nhwc, self.height, self.width, self.m_pass, self.m_eq, self.kernel) + + def release(self) -> None: + import ttnn + + if self._dev is not None: + for t in self._dev.values(): + if t is not None and t.is_allocated(): + ttnn.deallocate(t) + self._dev = None + + def describe(self) -> Dict[str, Any]: + return {"name": self.name, "grid": [self.height, self.width], "classes": self.classes, "rule": self.rule, + "kernel": self.kernel, "pooled_classes": [int(c) for c in np.flatnonzero(self.m_eq.max(axis=0))], + "passes": self.passes, "memory_config": str(self.memory_config)} diff --git a/code/tt_depthpro2/ttaw/ops/kernels/rerow_rm.cpp b/code/tt_depthpro2/ttaw/ops/kernels/rerow_rm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8bb29074bba53fdb4e4d806bccb76407a62c96b4 --- /dev/null +++ b/code/tt_depthpro2/ttaw/ops/kernels/rerow_rm.cpp @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: Apache-2.0 +// K12 rerow (ttaw 0.24.0, ops/rerow.py): a ROW_MAJOR DRAM-interleaved reshape that only changes the page width, +// [Rin, Win] -> [Rout, Wout] with Rin * Win == Rout * Wout and one page width a whole multiple M of the other, as a +// plain page copy at DRAM bandwidth (ttnn's RM reshape kernel: ~60 GB/s at METEOR's [864, 30720] -> [165888, 160]). +// The bytes of the logical row-major stream do not move; only their page (and so their DRAM bank) does. +// +// Terms: the "big" side has pages of M * PS bytes, the "small" side pages of PS bytes (PS % 64 == 0: every DRAM +// address and L1 offset below is 64 B aligned). A chunk = up to K consecutive small pages inside ONE big page +// (CPB = ceil(M / K) chunks per big page): one transfer of n * PS bytes at offset j0 * PS of big page b on the big +// side, n transfers of single pages b * M + j0 + t on the small side. DIR 0: big input -> small output (split), +// DIR 1: small input -> big output (join). +// One RISC / NOC does all reads and writes of a core (no two-NOC small DRAM writes: Blackhole SYS-1419). Two L1 +// slots: the reads of chunk q + 1 are in flight while chunk q is written. +// Work split (no per-core RT args, probe P3): core i = y * GX + x of the first NC cores owns chunks +// [i * B + min(i, E), + B + (i < E)), B = NCH / NC, E = NCH % NC. +// CT args: [0] NCH, [1] NC, [2] GX, [3] M, [4] K, [5] PS, [6] DIR, [7] CPB, [8] SLOT (bytes per slot, >= K * PS), +// then the TensorAccessorArgs of the input and of the output. Common RT args: [in_addr, out_addr]. +// CB 0: 2 * SLOT bytes, reserved never; used as plain L1 scratch through get_write_ptr. +#include + +#include "api/dataflow/dataflow_api.h" + +constexpr uint32_t NCH = get_compile_time_arg_val(0); +constexpr uint32_t NC = get_compile_time_arg_val(1); +constexpr uint32_t GX = get_compile_time_arg_val(2); +constexpr uint32_t M = get_compile_time_arg_val(3); +constexpr uint32_t K = get_compile_time_arg_val(4); +constexpr uint32_t PS = get_compile_time_arg_val(5); +constexpr uint32_t DIR = get_compile_time_arg_val(6); +constexpr uint32_t CPB = get_compile_time_arg_val(7); +constexpr uint32_t SLOT = get_compile_time_arg_val(8); +constexpr auto in_args = TensorAccessorArgs<9>(); +constexpr auto out_args = TensorAccessorArgs(); +constexpr uint32_t PB = M * PS; // big page bytes +constexpr uint32_t IN_PAGE = DIR == 0 ? PB : PS; +constexpr uint32_t OUT_PAGE = DIR == 0 ? PS : PB; + +template +FORCE_INLINE void big_read(const A& src, uint32_t b, uint32_t j0, uint32_t n, uint32_t buf) { + noc_async_read(src.get_noc_addr(b, j0 * PS), buf, n * PS); +} + +void kernel_main() { + const uint32_t core = get_absolute_logical_y() * GX + get_absolute_logical_x(); + if (core >= NC) { + return; + } + constexpr uint32_t B = NCH / NC, E = NCH % NC; + const uint32_t q0 = core * B + (core < E ? core : E); + const uint32_t nq = B + (core < E ? 1 : 0); + if (nq == 0) { + return; + } + const auto in = TensorAccessor(in_args, get_common_arg_val(0), IN_PAGE); + const auto out = TensorAccessor(out_args, get_common_arg_val(1), OUT_PAGE); + const uint32_t buf0 = get_write_ptr(0); + + auto issue_reads = [&](uint32_t q, uint32_t buf) { + const uint32_t b = q / CPB; + const uint32_t j0 = (q - b * CPB) * K; + const uint32_t n = (M - j0 < K) ? M - j0 : K; + if constexpr (DIR == 0) { + big_read(in, b, j0, n, buf); + } else { + const uint32_t p0 = b * M + j0; + for (uint32_t t = 0; t < n; ++t) { + noc_async_read(in.get_noc_addr(p0 + t), buf + t * PS, PS); + } + } + }; + auto issue_writes = [&](uint32_t q, uint32_t buf) { + const uint32_t b = q / CPB; + const uint32_t j0 = (q - b * CPB) * K; + const uint32_t n = (M - j0 < K) ? M - j0 : K; + if constexpr (DIR == 0) { + const uint32_t p0 = b * M + j0; + for (uint32_t t = 0; t < n; ++t) { + noc_async_write(buf + t * PS, out.get_noc_addr(p0 + t), PS); + } + } else { + noc_async_write(buf, out.get_noc_addr(b, j0 * PS), n * PS); + } + }; + + issue_reads(q0, buf0); + for (uint32_t i = 0; i < nq; ++i) { + const uint32_t buf = buf0 + (i & 1) * SLOT; + noc_async_read_barrier(); // chunk i is in its slot + if (i + 1 < nq) { + // the other slot held chunk i - 1, whose writes were flushed at the end of the previous iteration + issue_reads(q0 + i + 1, buf0 + ((i + 1) & 1) * SLOT); + } + issue_writes(q0 + i, buf); + noc_async_writes_flushed(); // chunk i has left L1: its slot may be refilled + } + noc_async_write_barrier(); +} diff --git a/code/tt_depthpro2/ttaw/ops/kernels/segment_reduce_dm.cpp b/code/tt_depthpro2/ttaw/ops/kernels/segment_reduce_dm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5f0edb5bc9482149cc7a82174db5e13fb9c486ff --- /dev/null +++ b/code/tt_depthpro2/ttaw/ops/kernels/segment_reduce_dm.cpp @@ -0,0 +1,536 @@ +// SPDX-License-Identifier: Apache-2.0 +// K1 segment_reduce (ttaw.ops.segment, PLAN.md 1.3): per-segment MAX over the rows of a tensor sorted by segment. +// +// out[s, :] = max(x[off[s] : off[s + 1], :]) for s in [0, NUM_SEG); empty segments -> FILL_BITS +// +// x: [1, 1, NUM_ROWS, C] interleaved DRAM, TILE (IN_TILE = 1) or ROW_MAJOR, bf16 or fp32; off: uint32 ROW_MAJOR +// [1, >= NUM_SEG + 1] interleaved DRAM (one page; CSR offsets, non-decreasing); out: [1, 1, NUM_SEG, C] ROW_MAJOR +// interleaved DRAM, bf16 (round to nearest even) or fp32. Exact: the maximum is taken on integer keys of the +// float bit patterns (key = bits ^ ((bits >> 31) & 0x7fffffff), signed order == float order, -0 < +0), so no float +// arithmetic happens on the RISC-V (no F extension) and bf16 / fp32 inputs come out bit-exact (fp32 -> bf16 is a +// monotonic rounding, so max-then-round == round-then-max). NaN is not supported (not produced by the models). +// +// Work split (deterministic, data-dependent, no per-core runtime args): NUM_WORKERS workers = SLOTS data-movement +// RISC-Vs per core on a GW-wide core rectangle starting at (X0, Y0); worker w = core_index * SLOTS + SLOT. The cost +// of segment s is off[s] + s (its rows plus one output row; strictly increasing in s), T = off[S] + S. Worker w owns +// the segments whose cost lies in [w T / W, (w + 1) T / W): it finds them by two binary searches over off (64-byte +// probes from DRAM), then streams its contiguous row range in units of 32 rows (one tile-row in TILE mode) with +// double buffering, reduces each segment into an L1 accumulator and writes one output row per segment (a ring of +// OUT_RING staging rows). Every segment is written by exactly one worker; nothing is shared between workers. +// +// Runtime args: COMMON only [x_addr, off_addr, out_addr] (P3 rule: per-core work derives from the core coordinates; +// the arg layout is fixed by the compile-time args). Hang-protocol notes (PLAN.md 4.4): no CB is pushed or popped +// (CBs are plain L1 scratch: data 2 units, offsets window, probe block, accumulator, output ring; sizes checked by +// the host builder), no multicast, no semaphores; every DRAM read has matching 64-byte alignment of source and +// destination (Blackhole NOC_DRAM_READ_ALIGNMENT_BYTES), every read is waited on by noc_async_read_barrier (which +// also invalidates the Blackhole L1 data cache) before the data are used, staging rows are reused only after +// noc_async_writes_flushed, and the kernel ends with noc_async_write_barrier. Offsets are clamped to [0, NUM_ROWS] +// and to non-decreasing order, so a corrupt table can never make the kernel read outside x. +#include + +#include "api/dataflow/dataflow_api.h" + +constexpr uint32_t IN_TILE = get_compile_time_arg_val(0); // 1: TILE input, 0: ROW_MAJOR input +constexpr uint32_t IN_BYTES = get_compile_time_arg_val(1); // input element bytes: 2 (bf16) or 4 (fp32) +constexpr uint32_t OUT_BYTES = get_compile_time_arg_val(2); // output element bytes: 2 (bf16, RNE) or 4 (fp32) +constexpr uint32_t C = get_compile_time_arg_val(3); // channels (multiple of 32) +constexpr uint32_t NUM_ROWS = get_compile_time_arg_val(4); // input rows (multiple of 32): the read bound +constexpr uint32_t NUM_SEG = get_compile_time_arg_val(5); // output rows (segments) +constexpr uint32_t NUM_WORKERS = get_compile_time_arg_val(6); // workers of the program +constexpr uint32_t SLOTS = get_compile_time_arg_val(7); // workers per core (1 or 2) +constexpr uint32_t SLOT = get_compile_time_arg_val(8); // this kernel's slot on its core +constexpr uint32_t X0 = get_compile_time_arg_val(9); // core rectangle: first logical x +constexpr uint32_t Y0 = get_compile_time_arg_val(10); // first logical y +constexpr uint32_t GW = get_compile_time_arg_val(11); // width in cores +constexpr uint32_t CB_DATA = get_compile_time_arg_val(12); // 2 units of input rows (+ 64 B alignment slack) +constexpr uint32_t CB_OFF = get_compile_time_arg_val(13); // offsets window: OFF_CHUNK uint32 (+ 64 B) +constexpr uint32_t CB_PROBE = get_compile_time_arg_val(14); // one 64-byte probe block (+ 64 B) +constexpr uint32_t CB_ACC = get_compile_time_arg_val(15); // C int32 keys +constexpr uint32_t CB_OUT = get_compile_time_arg_val(16); // OUT_RING output rows (+ 64 B) +constexpr uint32_t OUT_RING = get_compile_time_arg_val(17); // staging rows in flight +constexpr uint32_t OFF_CHUNK = get_compile_time_arg_val(18); // offsets per window (multiple of 16) +constexpr uint32_t FILL_BITS = get_compile_time_arg_val(19); // fp32 bits written for an empty segment +constexpr uint32_t OFF_PAGE_BYTES = get_compile_time_arg_val(20); // page (= tensor) size of off, bytes +constexpr uint32_t UNIT_PATH = get_compile_time_arg_val(21); // 1: in-register path for one-unit segments (0.23.4) +constexpr auto x_args = TensorAccessorArgs<22>(); +constexpr auto off_args = TensorAccessorArgs(); +constexpr auto out_args = TensorAccessorArgs(); + +constexpr uint32_t UNIT_ROWS = 32; // rows per streamed unit (one tile-row) +constexpr uint32_t CT = C / 32; // 32-column tiles per row +constexpr uint32_t TILE_ELEMS = 1024; +constexpr uint32_t IN_PAGE_BYTES = IN_TILE ? TILE_ELEMS * IN_BYTES : C * IN_BYTES; +constexpr uint32_t PAGES_PER_UNIT = IN_TILE ? CT : UNIT_ROWS; +constexpr uint32_t UNIT_BYTES = PAGES_PER_UNIT * IN_PAGE_BYTES; +constexpr uint32_t OUT_ROW_BYTES = C * OUT_BYTES; +constexpr uint32_t OFF_ALIGNED_BYTES = (OFF_PAGE_BYTES + 63u) & ~63u; +constexpr uint32_t NUM_UNITS = NUM_ROWS / UNIT_ROWS; + +static_assert(C % 32 == 0, "C must be a multiple of 32"); +static_assert(NUM_ROWS % UNIT_ROWS == 0, "NUM_ROWS must be a multiple of 32"); +static_assert(IN_BYTES == 2 || IN_BYTES == 4, "bf16 or fp32 input"); +static_assert(OUT_BYTES == 2 || OUT_BYTES == 4, "bf16 or fp32 output"); +static_assert(OFF_CHUNK % 16 == 0 && OFF_CHUNK >= 16, "OFF_CHUNK must be a multiple of 16"); +static_assert(OUT_RING >= 1, "OUT_RING >= 1"); +static_assert(IN_PAGE_BYTES % 64 == 0, "input pages must be 64-byte multiples (DRAM read alignment)"); +static_assert(OUT_ROW_BYTES % 16 == 0, "output rows must be 16-byte multiples (DRAM write alignment)"); + +#define COMPILER_BARRIER() asm volatile("" ::: "memory") + +#define ACC_LOCAL (C <= 256) +#if ACC_LOCAL +static int32_t acc_local[C]; +#endif + +static inline uint32_t align64(uint32_t a) { return (a + 63u) & ~63u; } + +// float bits <-> signed key (an involution); signed comparison of keys == float comparison (no NaN) +static inline int32_t to_key(uint32_t bits) { + const int32_t b = static_cast(bits); + return b ^ ((b >> 31) & 0x7fffffff); +} +static inline uint32_t from_key(int32_t k) { return static_cast(k ^ ((k >> 31) & 0x7fffffff)); } + +static inline uint16_t to_bf16_rne(uint32_t bits) { + return static_cast((bits + 0x7fffu + ((bits >> 16) & 1u)) >> 16); +} + +void kernel_main() { + const uint32_t x_addr = get_common_arg_val(0); + const uint32_t off_addr = get_common_arg_val(1); + const uint32_t out_addr = get_common_arg_val(2); + + const uint32_t core = (get_absolute_logical_y() - Y0) * GW + (get_absolute_logical_x() - X0); + const uint32_t w = core * SLOTS + SLOT; + if (w >= NUM_WORKERS) { + return; + } + + const auto xa = TensorAccessor(x_args, x_addr, IN_PAGE_BYTES); + const auto oa = TensorAccessor(off_args, off_addr, OFF_PAGE_BYTES); + const auto ya = TensorAccessor(out_args, out_addr, OUT_ROW_BYTES); + + const uint32_t data_l1 = align64(get_write_ptr(CB_DATA)); + const uint32_t off_l1 = align64(get_write_ptr(CB_OFF)); + const uint32_t probe_l1 = align64(get_write_ptr(CB_PROBE)); + const uint32_t out_l1 = align64(get_write_ptr(CB_OUT)); + // accumulator: in the RISC-V's local data memory (ACC_LOCAL, C <= 256: 1 KiB of .bss; 0.23.3) instead of L1 -- + // every input element costs one accumulator load and one store, which L1 makes the bottleneck +#if ACC_LOCAL + int32_t* acc = acc_local; +#else + int32_t* acc = reinterpret_cast(get_write_ptr(CB_ACC)); +#endif + + // ---- offsets: single 64-byte probes (binary search) and a streamed window (the worker's segments) + auto probe = [&](uint32_t s) -> uint32_t { + const uint32_t byte = s * 4u; + noc_async_read(oa.get_noc_addr(0, byte & ~63u), probe_l1, 64); + noc_async_read_barrier(); + COMPILER_BARRIER(); + const uint32_t v = reinterpret_cast(probe_l1)[(byte & 63u) >> 2]; + return v < NUM_ROWS ? v : NUM_ROWS; + }; + uint32_t win0 = 0xffffffffu; // first offset index held in the window (multiple of 16) + auto off_at = [&](uint32_t s) -> uint32_t { + if (win0 == 0xffffffffu || s < win0 || s >= win0 + OFF_CHUNK) { + win0 = s & ~15u; + const uint32_t start = win0 * 4u; + uint32_t bytes = OFF_CHUNK * 4u; + if (start + bytes > OFF_ALIGNED_BYTES) { + bytes = OFF_ALIGNED_BYTES - start; + } + noc_async_read(oa.get_noc_addr(0, start), off_l1, bytes); + noc_async_read_barrier(); + COMPILER_BARRIER(); + } + const uint32_t v = reinterpret_cast(off_l1)[s - win0]; + return v < NUM_ROWS ? v : NUM_ROWS; + }; + + // ---- this worker's segments [s_lo, s_hi): costs off[s] + s in [w T / W, (w + 1) T / W) + const uint32_t total = probe(NUM_SEG) + NUM_SEG; + auto search = [&](uint32_t target) -> uint32_t { // smallest s in [0, NUM_SEG] with off[s] + s >= target + uint32_t lo = 0, hi = NUM_SEG; + while (lo < hi) { + const uint32_t mid = (lo + hi) >> 1; + if (probe(mid) + mid >= target) { + hi = mid; + } else { + lo = mid + 1; + } + } + return lo; + }; + const uint32_t t0 = static_cast((static_cast(w) * total) / NUM_WORKERS); + const uint32_t t1 = static_cast((static_cast(w + 1) * total) / NUM_WORKERS); + const uint32_t s_lo = (w == 0) ? 0 : search(t0); + const uint32_t s_hi = (w + 1 == NUM_WORKERS) ? NUM_SEG : search(t1); + if (s_lo >= s_hi) { + return; + } + + // ---- input rows: units of 32 rows, two L1 slots, the next unit prefetched while the current one is reduced + uint32_t row_last = off_at(s_lo); // largest row this worker reads (+1), monotone over its segments + { + const uint32_t r_end = off_at(s_hi); + if (r_end > row_last) { + row_last = r_end; + } + } + const uint32_t unit_last = row_last > 0 ? (row_last - 1) / UNIT_ROWS : 0; + auto issue_unit = [&](uint32_t u, uint32_t slot) { + const uint32_t dst = data_l1 + slot * UNIT_BYTES; + const uint32_t first_page = IN_TILE ? u * CT : u * UNIT_ROWS; + for (uint32_t p = 0; p < PAGES_PER_UNIT; ++p) { + noc_async_read(xa.get_noc_addr(first_page + p), dst + p * IN_PAGE_BYTES, IN_PAGE_BYTES); + } + }; + uint32_t cur_unit = 0xffffffffu, cur_slot = 0; + bool next_ready = false; // the unit cur_unit + 1 is in flight into slot cur_slot ^ 1 + auto ensure_unit = [&](uint32_t u) { + if (u == cur_unit) { + return; + } + if (next_ready && u == cur_unit + 1) { + noc_async_read_barrier(); + cur_slot ^= 1u; + } else { + noc_async_read_barrier(); // drain a stale prefetch before its slot is reused + issue_unit(u, cur_slot); + noc_async_read_barrier(); + } + COMPILER_BARRIER(); + cur_unit = u; + next_ready = false; + if (u + 1 <= unit_last && u + 1 < NUM_UNITS) { + issue_unit(u + 1, cur_slot ^ 1u); + next_ready = true; + } + }; + + // acc = max(acc, x[r, :]) on keys; FIRST: acc = keys of x[r, :] (the first row of a segment: the same result as + // max(INT32_MIN, key), without the reset pass; 0.23.3). The data slot is plain memory here: the reads that filled + // it were waited on by noc_async_read_barrier (which also invalidates the Blackhole L1 data cache) and the + // COMPILER_BARRIER after it orders the loads, so the loads need not be volatile (0.23.3: lets them pipeline). + auto accumulate_row = [&](uint32_t r, bool first) { + const uint32_t i = r - cur_unit * UNIT_ROWS; + const uint32_t base = data_l1 + cur_slot * UNIT_BYTES; + if constexpr (IN_TILE) { + const uint32_t face_row = (i >> 4) << 1; // faces 0/1 (rows 0-15) or 2/3 (rows 16-31) + for (uint32_t tc = 0; tc < CT; ++tc) { + for (uint32_t h = 0; h < 2; ++h) { + const uint32_t e0 = tc * TILE_ELEMS + (face_row + h) * 256 + (i & 15u) * 16; + int32_t* a = acc + tc * 32 + h * 16; + if constexpr (IN_BYTES == 4) { + const uint32_t* src = reinterpret_cast(base) + e0; + if (first) { +#pragma GCC unroll 16 + for (uint32_t k = 0; k < 16; ++k) { + a[k] = to_key(src[k]); + } + } else { +#pragma GCC unroll 16 + for (uint32_t k = 0; k < 16; ++k) { + const int32_t key = to_key(src[k]); + a[k] = key > a[k] ? key : a[k]; + } + } + } else { + const uint16_t* src = reinterpret_cast(base) + e0; + if (first) { +#pragma GCC unroll 16 + for (uint32_t k = 0; k < 16; ++k) { + a[k] = to_key(static_cast(src[k]) << 16); + } + } else { +#pragma GCC unroll 16 + for (uint32_t k = 0; k < 16; ++k) { + const int32_t key = to_key(static_cast(src[k]) << 16); + a[k] = key > a[k] ? key : a[k]; + } + } + } + } + } + } else { + if constexpr (IN_BYTES == 4) { + const uint32_t* src = reinterpret_cast(base) + i * C; + for (uint32_t c = 0; c < C; ++c) { + const int32_t key = to_key(src[c]); + acc[c] = (first || key > acc[c]) ? key : acc[c]; + } + } else { + const uint16_t* src = reinterpret_cast(base) + i * C; + for (uint32_t c = 0; c < C; ++c) { + const int32_t key = to_key(static_cast(src[c]) << 16); + acc[c] = (first || key > acc[c]) ? key : acc[c]; + } + } + } + }; + + // ---- output rows: a ring of OUT_RING staging rows, reused after noc_async_writes_flushed. fill_mask (0.23.4): + // the ring slots that already hold the empty-segment row, so a run of empty segments (every segment past the + // frame's M) is written from L1 without re-filling the row + static_assert(OUT_RING <= 32, "fill_mask holds 32 ring slots"); + uint32_t emitted = 0; + uint32_t fill_mask = 0; + auto stage = [&]() -> uint32_t { + const uint32_t ring = emitted % OUT_RING; + if (ring == 0 && emitted > 0) { + noc_async_writes_flushed(); + } + fill_mask &= ~(1u << ring); + return out_l1 + ring * OUT_ROW_BYTES; + }; + auto send = [&](uint32_t dst, uint32_t s) { + COMPILER_BARRIER(); + noc_async_write(dst, ya.get_noc_addr(s), OUT_ROW_BYTES); + ++emitted; + }; + auto emit = [&](uint32_t s, bool empty) { + const uint32_t ring = emitted % OUT_RING; + if (empty && (fill_mask & (1u << ring))) { // the slot still holds the fill row (0.23.4) + if (ring == 0 && emitted > 0) { + noc_async_writes_flushed(); + } + send(out_l1 + ring * OUT_ROW_BYTES, s); + return; + } + const uint32_t dst = stage(); + if (empty) { + fill_mask |= 1u << ring; + } + if constexpr (OUT_BYTES == 4) { + volatile tt_l1_ptr uint32_t* o = reinterpret_cast(dst); + for (uint32_t c = 0; c < C; ++c) { + o[c] = empty ? FILL_BITS : from_key(acc[c]); + } + } else { + volatile tt_l1_ptr uint16_t* o = reinterpret_cast(dst); + const uint16_t fill = to_bf16_rne(FILL_BITS); + for (uint32_t c = 0; c < C; ++c) { + o[c] = empty ? fill : to_bf16_rne(from_key(acc[c])); + } + } + send(dst, s); + }; + // one-row segment (0.23.3): its max is the row itself (from_key(to_key(b)) == b), so the row is converted to the + // output dtype straight from the data slot (the same RNE for bf16 outputs), without the accumulator + auto emit_row = [&](uint32_t s, uint32_t r) { + ensure_unit(r / UNIT_ROWS); + const uint32_t i = r - cur_unit * UNIT_ROWS; + const uint32_t base = data_l1 + cur_slot * UNIT_BYTES; + const uint32_t dst = stage(); + auto put = [&](uint32_t c, uint32_t bits32) { + if constexpr (OUT_BYTES == 4) { + reinterpret_cast(dst)[c] = bits32; + } else { + reinterpret_cast(dst)[c] = to_bf16_rne(bits32); + } + }; + if constexpr (IN_TILE) { + const uint32_t face_row = (i >> 4) << 1; + for (uint32_t tc = 0; tc < CT; ++tc) { + for (uint32_t h = 0; h < 2; ++h) { + const uint32_t e0 = tc * TILE_ELEMS + (face_row + h) * 256 + (i & 15u) * 16; + const uint32_t c0 = tc * 32 + h * 16; + if constexpr (OUT_BYTES == 2 && UNIT_PATH) { + // 0.23.4: bf16 outputs as packed pairs (one 32-bit store per two channels); a bf16 input + // pair is its own output word (RNE of a bf16-exact value is the value) + volatile tt_l1_ptr uint32_t* o = reinterpret_cast(dst) + (c0 >> 1); + if constexpr (IN_BYTES == 4) { + const uint32_t* src = reinterpret_cast(base) + e0; +#pragma GCC unroll 8 + for (uint32_t k = 0; k < 8; ++k) { + o[k] = static_cast(to_bf16_rne(src[2 * k])) | + (static_cast(to_bf16_rne(src[2 * k + 1])) << 16); + } + } else { + const uint32_t* src = reinterpret_cast(base) + (e0 >> 1); +#pragma GCC unroll 8 + for (uint32_t k = 0; k < 8; ++k) { + o[k] = src[k]; + } + } + } else if constexpr (IN_BYTES == 4) { + const uint32_t* src = reinterpret_cast(base) + e0; +#pragma GCC unroll 16 + for (uint32_t k = 0; k < 16; ++k) { + put(c0 + k, src[k]); + } + } else { + const uint16_t* src = reinterpret_cast(base) + e0; +#pragma GCC unroll 16 + for (uint32_t k = 0; k < 16; ++k) { + put(c0 + k, static_cast(src[k]) << 16); + } + } + } + } + } else { + if constexpr (IN_BYTES == 4) { + const uint32_t* src = reinterpret_cast(base) + i * C; + for (uint32_t c = 0; c < C; ++c) { + put(c, src[c]); + } + } else { + const uint16_t* src = reinterpret_cast(base) + i * C; + for (uint32_t c = 0; c < C; ++c) { + put(c, static_cast(src[c]) << 16); + } + } + } + send(dst, s); + }; + + // keys of the max over rows [i0, i1) of one 8-column group (element offset eq within a row's face row) of the TILE + // data: rows < UNIT_ROWS in slot base0, the next unit's rows in base1 (0.23.4). The maximum stays in registers + // (8 independent loads per row, no accumulator traffic); the same integer keys as accumulate_row. + auto group_keys = [&](uint32_t base0, uint32_t base1, uint32_t i0, uint32_t i1, uint32_t eq, int32_t* k) + __attribute__((always_inline)) { + { + const uint32_t base = i0 < UNIT_ROWS ? base0 : base1; + const uint32_t ii = i0 & (UNIT_ROWS - 1); + const uint32_t e = eq + ((ii >> 4) << 9) + (ii & 15u) * 16; + if constexpr (IN_BYTES == 4) { + const uint32_t* src = reinterpret_cast(base) + e; +#pragma GCC unroll 8 + for (uint32_t j = 0; j < 8; ++j) { + k[j] = to_key(src[j]); + } + } else { + const uint16_t* src = reinterpret_cast(base) + e; +#pragma GCC unroll 8 + for (uint32_t j = 0; j < 8; ++j) { + k[j] = to_key(static_cast(src[j]) << 16); + } + } + } + for (uint32_t i = i0 + 1; i < i1; ++i) { + const uint32_t base = i < UNIT_ROWS ? base0 : base1; + const uint32_t ii = i & (UNIT_ROWS - 1); + const uint32_t e = eq + ((ii >> 4) << 9) + (ii & 15u) * 16; + uint32_t v[8]; + if constexpr (IN_BYTES == 4) { + const uint32_t* src = reinterpret_cast(base) + e; +#pragma GCC unroll 8 + for (uint32_t j = 0; j < 8; ++j) { + v[j] = src[j]; + } + } else { + const uint16_t* src = reinterpret_cast(base) + e; +#pragma GCC unroll 8 + for (uint32_t j = 0; j < 8; ++j) { + v[j] = static_cast(src[j]) << 16; + } + } +#pragma GCC unroll 8 + for (uint32_t j = 0; j < 8; ++j) { + const int32_t key = to_key(v[j]); + k[j] = key > k[j] ? key : k[j]; + } + } + }; + + // a segment whose rows lie in one 32-row unit or in two consecutive ones (TILE input; 0.23.4): group_keys per + // 8-column group, converted straight into the output row (bf16 outputs as packed pairs, one 32-bit store per two + // channels). A segment reaching into the next unit uses its prefetch, waited on here (ensure_unit issued it into + // the other slot; the next ensure_unit flips to it as usual). The same integer-key max and the same RNE as the + // accumulator path: bit-identical. + auto emit_seg_unit = [&](uint32_t s, uint32_t r0, uint32_t r1) { + ensure_unit(r0 / UNIT_ROWS); + if ((r1 - 1) / UNIT_ROWS != cur_unit) { + noc_async_read_barrier(); // the prefetch of cur_unit + 1 into slot cur_slot ^ 1 + COMPILER_BARRIER(); + } + const uint32_t i0 = r0 - cur_unit * UNIT_ROWS; + const uint32_t i1 = r1 - cur_unit * UNIT_ROWS; // <= 2 * UNIT_ROWS + const uint32_t base0 = data_l1 + cur_slot * UNIT_BYTES; + const uint32_t base1 = data_l1 + (cur_slot ^ 1u) * UNIT_BYTES; + const uint32_t dst = stage(); + for (uint32_t tc = 0; tc < CT; ++tc) { + for (uint32_t h = 0; h < 2; ++h) { +#pragma GCC unroll 2 + for (uint32_t q = 0; q < 2; ++q) { + const uint32_t col = tc * 32 + h * 16 + q * 8; + int32_t k[8]; + group_keys(base0, base1, i0, i1, tc * TILE_ELEMS + h * 256 + q * 8, k); + if constexpr (OUT_BYTES == 4) { + volatile tt_l1_ptr uint32_t* o = reinterpret_cast(dst) + col; +#pragma GCC unroll 8 + for (uint32_t j = 0; j < 8; ++j) { + o[j] = from_key(k[j]); + } + } else { + volatile tt_l1_ptr uint32_t* o = + reinterpret_cast(dst) + (col >> 1); +#pragma GCC unroll 4 + for (uint32_t j = 0; j < 4; ++j) { + o[j] = static_cast(to_bf16_rne(from_key(k[2 * j]))) | + (static_cast(to_bf16_rne(from_key(k[2 * j + 1]))) << 16); + } + } + } + } + } + send(dst, s); + }; + + // a longer segment (TILE input; 0.23.4): group_keys over each unit's part of it, merged into the accumulator + // (the first part initialises it), then emitted as before + auto reduce_long = [&](uint32_t r0, uint32_t r1) { + for (uint32_t r = r0; r < r1;) { + const uint32_t u = r / UNIT_ROWS; + const uint32_t re = r1 < (u + 1) * UNIT_ROWS ? r1 : (u + 1) * UNIT_ROWS; + ensure_unit(u); + const uint32_t base = data_l1 + cur_slot * UNIT_BYTES; + const bool first = r == r0; + for (uint32_t tc = 0; tc < CT; ++tc) { + for (uint32_t h = 0; h < 2; ++h) { +#pragma GCC unroll 2 + for (uint32_t q = 0; q < 2; ++q) { + int32_t k[8]; + group_keys(base, base, r - u * UNIT_ROWS, re - u * UNIT_ROWS, tc * TILE_ELEMS + h * 256 + q * 8, + k); + int32_t* a = acc + tc * 32 + h * 16 + q * 8; +#pragma GCC unroll 8 + for (uint32_t j = 0; j < 8; ++j) { + a[j] = (first || k[j] > a[j]) ? k[j] : a[j]; + } + } + } + } + r = re; + } + }; + + // ---- the reduction + uint32_t seg_begin = off_at(s_lo); + for (uint32_t s = s_lo; s < s_hi; ++s) { + uint32_t seg_end = off_at(s + 1); + if (seg_end < seg_begin) { + seg_end = seg_begin; // non-decreasing offsets (a corrupt table reads nothing extra) + } + if (seg_end == seg_begin) { + emit(s, true); + } else if (seg_end == seg_begin + 1) { + emit_row(s, seg_begin); + } else if (IN_TILE && UNIT_PATH && (seg_end - 1) / UNIT_ROWS - seg_begin / UNIT_ROWS <= 1u) { + emit_seg_unit(s, seg_begin, seg_end); + } else if (IN_TILE && UNIT_PATH) { + reduce_long(seg_begin, seg_end); + emit(s, false); + } else { + for (uint32_t r = seg_begin; r < seg_end; ++r) { + ensure_unit(r / UNIT_ROWS); + accumulate_row(r, r == seg_begin); + } + emit(s, false); + } + seg_begin = seg_end; + } + noc_async_read_barrier(); // a prefetch past the last row may still be in flight + noc_async_write_barrier(); +} diff --git a/code/tt_depthpro2/ttaw/ops/rerow.py b/code/tt_depthpro2/ttaw/ops/rerow.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f9fdde7ef1269c138f9be271683e5dd0c82ff2 --- /dev/null +++ b/code/tt_depthpro2/ttaw/ops/rerow.py @@ -0,0 +1,180 @@ +# SPDX-License-Identifier: Apache-2.0 +"""K12 ``rerow`` (0.24.0): a ROW_MAJOR reshape that only changes the page width, as one data-movement ``generic_op``. + +A ROW_MAJOR DRAM-interleaved tensor ``[.., Rin, Win]`` viewed as ``[1, 1, Rout, Wout]`` (``Rin * Win == Rout * +Wout``) keeps its logical byte stream; only the page size, and so the DRAM bank of every byte, changes. ttnn's RM +reshape does this at ~60 GB/s at the C18 ``Resize2d`` shapes (METEOR ``[864, 30720] -> [165888, 160]`` fp32: 1.72 ms +for 106 MB moved). :func:`rerow` does it as a page copy (kernel ``kernels/rerow_rm.cpp``) when one page width is a +whole multiple ``M`` of the other and the smaller page is a multiple of 64 B (every DRAM address and L1 offset of +the copy is then 64 B aligned); otherwise it falls back to ``ttnn.reshape``. Bit-identical by construction (bytes +are copied, never converted). + +Kernel: chunks of up to ``K`` small pages inside one big page (one transfer on the big side, ``n`` page transfers on +the small side), split evenly over the device's compute grid (``compute_with_storage_grid_size()``: ETH 12x10 and +WORKER 11x10 alike); one RISC / NOC per core does the reads and the writes (no two-NOC small DRAM writes, Blackhole +SYS-1419), double-buffered. Parameters: COMPILE = chunk count, grid, M, K, page bytes, direction (split / join); +per call = the two buffer addresses (common RT args: probe P3). + +Measured (p150, ETH 12x10, traced, bit-identical to ``ttnn.reshape``; ``bundles/meteor-p150/code/scripts/ +rerow_probe.py``, ``logs/meteor/opt_r5/job1_probe.log``): splits (big -> small pages) [864, 30720] -> [165888, 160] +fp32 1.755 -> 0.846 ms, [800, 48000] -> [400000, 96] bf16 1.282 -> 0.722, [864, 18432] -> [165888, 96] fp32 1.117 -> +0.514, [800, 32000] -> [400000, 64] bf16 1.064 -> 0.526, [400, 32000] -> [100000, 128] fp32 0.904 -> 0.397 ms; joins +(small -> big) are SLOWER than ttnn's reshape ([82944, 160] -> [432, 30720] 0.353 -> 0.511, [200000, 96] -> [400, +48000] 0.676 -> 0.887 ms), so :func:`rerow` leaves them to ttnn unless ``joins=True``. +""" +from __future__ import annotations + +import os +from dataclasses import dataclass +from typing import Any, Optional, Tuple + +from . import kernel_path + +__all__ = ["RerowPlan", "rerow_plan", "rerow", "rerow_reference", "KERNEL", "CHUNK_BYTES", "REROW_MODES"] + +KERNEL = "rerow_rm.cpp" +CHUNK_BYTES = 32 * 1024 # bytes per L1 slot (two slots per core) +REROW_MODES = ("stock", "kernel") + + +@dataclass(frozen=True) +class RerowPlan: + rows_in: int + rows_out: int + page_in: int # bytes + page_out: int + direction: int # 0: split (input pages are the big ones), 1: join + m: int # small pages per big page + small: int # small page bytes + k: int # small pages per chunk + cpb: int # chunks per big page + chunks: int + slot: int # bytes per L1 slot + + @property + def big_pages(self) -> int: + return self.rows_in if self.direction == 0 else self.rows_out + + +def rerow_plan(rows_in: int, width_in: int, rows_out: int, width_out: int, elem_bytes: int, + chunk_bytes: int = CHUNK_BYTES) -> Optional[RerowPlan]: + """The kernel's plan for ``[rows_in, width_in] -> [rows_out, width_out]``, or None when the kernel does not + apply (the caller falls back to ``ttnn.reshape``).""" + rows_in, width_in, rows_out, width_out = int(rows_in), int(width_in), int(rows_out), int(width_out) + if rows_in * width_in != rows_out * width_out or min(rows_in, width_in, rows_out, width_out) <= 0: + raise ValueError(f"rerow: [{rows_in}, {width_in}] -> [{rows_out}, {width_out}] changes the volume") + p_in, p_out = width_in * elem_bytes, width_out * elem_bytes + if p_in == p_out: + return None # a view: nothing to copy + big, small = max(p_in, p_out), min(p_in, p_out) + if big % small or small % 64: + return None + m = big // small + k = max(1, min(m, chunk_bytes // small)) + if k * small > max(chunk_bytes, small): + return None + cpb = -(-m // k) + direction = 0 if p_in > p_out else 1 + big_pages = rows_in if direction == 0 else rows_out + return RerowPlan(rows_in, rows_out, p_in, p_out, direction, m, small, k, cpb, big_pages * cpb, k * small) + + +def rerow_reference(stream_in, plan: RerowPlan): + """Host emulation of the kernel's page moves on a flat numpy byte array (tests): each chunk copies its big-side + byte range and its ``n`` small pages; returns ``(output stream, per-byte write count)``. The logical stream does + not move, so a correct plan gives the input back with every byte written exactly once.""" + import numpy as np + + src = np.asarray(stream_in, np.uint8).reshape(-1) + dst = np.zeros_like(src) + hits = np.zeros(src.shape, np.int32) + for q in range(plan.chunks): + b, c = divmod(q, plan.cpb) + j0 = c * plan.k + n = min(plan.k, plan.m - j0) + big0 = (b * plan.m + j0) * plan.small # big page b, offset j0 * PS + for t in range(n): # small page b * M + j0 + t + p = b * plan.m + j0 + t + if plan.direction == 0: # big in -> small out + dst[p * plan.small:(p + 1) * plan.small] = src[big0 + t * plan.small:big0 + (t + 1) * plan.small] + hits[p * plan.small:(p + 1) * plan.small] += 1 + else: # small in -> big out + dst[big0 + t * plan.small:big0 + (t + 1) * plan.small] = src[p * plan.small:(p + 1) * plan.small] + hits[big0 + t * plan.small:big0 + (t + 1) * plan.small] += 1 + return dst, hits + + +def _supported(t: Any) -> bool: + import ttnn + + if not hasattr(ttnn, "generic_op") or t.layout != ttnn.ROW_MAJOR_LAYOUT: + return False + mc = t.memory_config() + return (getattr(mc, "buffer_type", None) == ttnn.BufferType.DRAM + and getattr(mc, "memory_layout", None) == ttnn.TensorMemoryLayout.INTERLEAVED) + + +def _elem_bytes(t: Any) -> Optional[int]: + import ttnn + + return {ttnn.float32: 4, ttnn.bfloat16: 2, ttnn.uint32: 4, ttnn.int32: 4, ttnn.uint16: 2, + ttnn.uint8: 1}.get(t.dtype) + + +def rerow(t: Any, shape: Tuple[int, int, int, int], *, mode: str = "kernel", joins: bool = False) -> Any: + """``ttnn.reshape(t, shape)`` for a ROW_MAJOR DRAM-interleaved ``t`` and a 4-D ``shape`` ``(1, 1, R, W)``; with + ``mode="kernel"`` the page re-cut runs as the K12 kernel where it applies (module docstring), else stock. + Joins (small pages -> big pages) take ttnn's reshape unless ``joins=True``: it is faster there (module + docstring, measured).""" + import ttnn + + shape = tuple(int(s) for s in shape) + if mode != "kernel" or len(shape) != 4 or shape[0] != 1 or shape[1] != 1 or not _supported(t): + return ttnn.reshape(t, shape) + eb = _elem_bytes(t) + in_shape = [int(s) for s in t.shape] + w_in = in_shape[-1] + r_in = 1 + for s in in_shape[:-1]: + r_in *= s + plan = None if eb is None else rerow_plan(r_in, w_in, shape[2], shape[3], eb) + if plan is None or (plan.direction == 1 and not joins): + return ttnn.reshape(t, shape) + dev = t.device() + out = ttnn.allocate_tensor_on_device(ttnn.Shape(list(shape)), t.dtype, ttnn.ROW_MAJOR_LAYOUT, dev, + ttnn.DRAM_MEMORY_CONFIG) + ttnn.generic_op([t, out], program(t, out, plan)) + return out + + +def program(t: Any, out: Any, plan: RerowPlan): + """The ``ttnn.ProgramDescriptor`` of one call (buffer addresses in common runtime args).""" + import ttnn + + g = t.device().compute_with_storage_grid_size() + gx, gy = int(g.x), int(g.y) + nc = max(1, min(plan.chunks, gx * gy)) + full, rem = divmod(nc, gx) + rs = [] + if full: + rs.append(ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(gx - 1, full - 1))) + if rem: + rs.append(ttnn.CoreRange(ttnn.CoreCoord(0, full), ttnn.CoreCoord(rem - 1, full))) + crs = ttnn.CoreRangeSet(set(rs)) + cbs = [ttnn.CBDescriptor(total_size=2 * plan.slot, core_ranges=crs, format_descriptors=[ + ttnn.CBFormatDescriptor(buffer_index=0, data_format=ttnn.uint8, page_size=plan.slot)])] + ct = [plan.chunks, nc, gx, plan.m, plan.k, plan.small, plan.direction, plan.cpb, plan.slot] \ + + list(ttnn.TensorAccessorArgs(t).get_compile_time_args()) \ + + list(ttnn.TensorAccessorArgs(out).get_compile_time_args()) + k = ttnn.KernelDescriptor(kernel_source=kernel_path(KERNEL), source_type=ttnn.KernelDescriptor.SourceType.FILE_PATH, + core_ranges=crs, compile_time_args=ct, defines=[], runtime_args=ttnn.RuntimeArgs(), + common_runtime_args=[t.buffer_address(), out.buffer_address()], + config=ttnn.ReaderConfigDescriptor()) + return ttnn.ProgramDescriptor(kernels=[k], semaphores=[], cbs=cbs) + + +def mode_from_env(default: str = "stock", var: str = "TTAW_REROW") -> str: + mode = (os.environ.get(var) or default).strip().lower() + if mode not in REROW_MODES: + raise ValueError(f"{var}={mode!r}: expected one of {REROW_MODES}") + return mode diff --git a/code/tt_depthpro2/ttaw/ops/segment.py b/code/tt_depthpro2/ttaw/ops/segment.py new file mode 100644 index 0000000000000000000000000000000000000000..3ee778c73ef220cc919246b676ca1cc559d752f1 --- /dev/null +++ b/code/tt_depthpro2/ttaw/ops/segment.py @@ -0,0 +1,448 @@ +# SPDX-License-Identifier: Apache-2.0 +"""K1 ``segment_reduce``: per-segment reductions over rows sorted by segment (PLAN.md section 1.3 row K1; owned by the +FRNet port), with the exact stock-op fallback (the log-step segmented max) and their host twins. + +A *segmented* tensor holds rows sorted by segment id: segment ``s`` is the contiguous row range +``[offsets[s], offsets[s + 1])`` (CSR offsets, non-decreasing; rows past ``offsets[-1]`` are padding that nothing +reads). FRNet's six ``ScatterElements(max)`` sites (points sorted by frustum cell, PLAN.md 2.8), PTv3 pooling and +BEVPool are of this form once the host sorts the rows. + +- **K1 on the device** (:class:`SegmentReduce`, kernel ``kernels/segment_reduce_dm.cpp``): ``out[s] = + max(x[offsets[s]:offsets[s + 1]])`` for ``s < num_segments``, empty segments -> ``empty_value`` (FRNet: the zero + row of the frustum2pixel gather table comes out of the kernel itself). Input ``[1, 1, R, C]`` TILE or ROW_MAJOR, + bf16 or fp32 (``R % 32 == 0``, ``C % 32 == 0``); offsets uint32 ``[1, K]`` ROW_MAJOR (``K >= num_segments + 1``, + an RT-dev tensor: rewritten per frame, no recapture); output ``[1, 1, num_segments, C]`` ROW_MAJOR, bf16 (round to + nearest even) or fp32 -- the layout ``ttnn.embedding`` takes as a table. **Exact**: the maximum is taken on + integer keys of the float bit patterns (signed order == float order, -0 < +0), so the result is bit-exact for any + input dtype, and fp32 -> bf16 output equals rounding first (a monotonic rounding commutes with max). One program, + common runtime args only (probe P3 rule), deterministic, no atomics, traceable. Work split: 2 data-movement + RISC-Vs per core, each a contiguous run of segments balanced on rows + 1 per segment, found on the device by binary + search over the offsets (no per-frame host split, nothing grid-dependent in the host tables). +- **max only on the device for now.** ``sum`` / ``mean`` need float adds, which the data-movement RISC-Vs do not have + (no F extension); they are host-oracle only here (:func:`segment_reduce_numpy`) and come with their consumers + (PTv3 / BEVPool, optimization phase). +- **Stock-op fallback** (:func:`logstep_segment_max`, PLAN.md 1.3): ``R`` Hillis-Steele rounds ``x = max(x, x[idx_r])`` + with host shift tables ``idx_r[i] = i - 2^r`` when row ``i - 2^r`` is in the same segment, else ``i`` (max is + idempotent), then one gather of each segment's last row: exact for segments of up to ``2^R`` rows, ``3R + 1`` + programs (untilize, ``ttnn.embedding``, ``ttnn.maximum`` per round). ``ttnn.embedding`` is bf16-only, so the + fallback is bf16 in and out. ``R`` is COMPILE (it sets the op count): bucket it per frame (:func:`segment_rounds`). + +Host side (numpy only): :func:`segment_offsets` (CSR offsets from sorted segment ids), :func:`segment_rounds`, +:func:`segment_shift_tables`, :func:`segment_last_rows`, oracles :func:`segment_reduce_numpy` and +:func:`logstep_segment_max_numpy`, and :func:`worker_segments` (the kernel's work split, for tests and diagnostics). +numpy only at import; ttnn is imported inside the device functions. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Sequence, Tuple + +import numpy as np + +from . import kernel_path + +__all__ = [ + "OPS", + "DEVICE_OPS", + "segment_offsets", + "check_offsets", + "segment_rounds", + "segment_shift_tables", + "segment_last_rows", + "segment_reduce_numpy", + "logstep_segment_max_numpy", + "worker_segments", + "SegmentReduceSpec", + "SegmentReduce", + "segment_reduce", + "logstep_segment_max", + "KERNEL", +] + +OPS = ("max", "min", "sum", "mean") +DEVICE_OPS = ("max",) +KERNEL = "segment_reduce_dm.cpp" +UNIT_ROWS = 32 # rows per streamed unit (one tile-row): the input rows must be a multiple of it +_OFF_CHUNK = 256 # offsets per L1 window (multiple of 16) +_OUT_RING = 8 # output staging rows in flight per worker + + +# ------------------------------------------------------------------------------------------------ host tables + +def segment_offsets(seg_id: Any, num_segments: int, *, num_rows: Optional[int] = None) -> np.ndarray: + """CSR offsets ``uint32 [num_segments + 1]`` of rows sorted by segment id: segment ``s`` = rows + ``[off[s], off[s + 1])``. ``seg_id`` (``int [R]``, non-decreasing) may contain ids ``>= num_segments`` (padding + rows, e.g. FRNet's trailing sentinel segment): they must come last and belong to no segment. ``num_rows`` + (default ``len(seg_id)``) bounds the offsets.""" + ids = np.asarray(seg_id).reshape(-1).astype(np.int64) + if ids.size and (np.any(np.diff(ids) < 0) or ids[0] < 0): + raise ValueError("segment ids must be non-negative and sorted (non-decreasing)") + counts = np.bincount(ids[ids < num_segments], minlength=num_segments).astype(np.int64) + off = np.zeros(num_segments + 1, np.int64) + np.cumsum(counts, out=off[1:]) + rows = len(ids) if num_rows is None else int(num_rows) + if off[-1] > rows: + raise ValueError(f"segments hold {off[-1]} rows, more than num_rows={rows}") + return off.astype(np.uint32) + + +def check_offsets(offsets: Any, *, num_segments: int, num_rows: int, length: Optional[int] = None) -> np.ndarray: + """Validate CSR offsets for the device and return them as a contiguous ``uint32 [1, length]`` row (``length`` + defaults to ``num_segments + 1``; extra entries repeat the last offset). Raises ``ValueError`` unless they start + at 0, never decrease and end at most at ``num_rows`` (the kernel clamps anyway; a bad table is a host bug).""" + a = np.asarray(offsets).reshape(-1) + if a.dtype.kind not in "iu": + raise ValueError(f"offsets must be integral, got dtype {a.dtype}") + a = a.astype(np.int64) + if a.size < num_segments + 1: + raise ValueError(f"{a.size} offsets for {num_segments} segments (need num_segments + 1)") + a = a[: num_segments + 1] + if a[0] != 0 or np.any(np.diff(a) < 0) or a[-1] > num_rows: + raise ValueError(f"offsets must start at 0, be non-decreasing and end <= num_rows={num_rows}") + n = num_segments + 1 if length is None else int(length) + if n < num_segments + 1: + raise ValueError(f"length {n} < num_segments + 1") + out = np.full((1, n), a[-1], np.uint32) + out[0, : a.size] = a + return out + + +def segment_rounds(max_segment_length: int) -> int: + """Log-step rounds that cover segments of up to ``max_segment_length`` rows: ``ceil(log2(L))`` (0 for L <= 1).""" + L = int(max_segment_length) + return int(np.ceil(np.log2(L))) if L > 1 else 0 + + +def segment_shift_tables(seg_id: Any, rounds: int) -> List[np.ndarray]: + """The gather tables of the log-step segmented max: round ``r`` uses ``idx[i] = i - 2^r`` if row ``i - 2^r`` has + the same segment id, else ``i`` -> ``rounds`` x ``uint32 [R]``. After ``rounds`` rounds the last row of every + segment of at most ``2^rounds`` rows holds the segment max (padding rows only ever see padding rows).""" + seg = np.asarray(seg_id).reshape(-1) + i = np.arange(len(seg), dtype=np.int64) + out = [] + for r in range(int(rounds)): + d = 1 << r + same = np.zeros(len(seg), bool) + same[d:] = seg[d:] == seg[:-d] + out.append(np.where(same, i - d, i).astype(np.uint32)) + return out + + +def segment_last_rows(offsets: Any, *, empty_row: int) -> np.ndarray: + """``uint32 [S]``: the last row of each segment of ``offsets`` (``S + 1`` entries), ``empty_row`` for an empty + segment. For :func:`logstep_segment_max` pass the number of input rows: the fallback appends one zero row there + (padding rows themselves are reduced too, so they do not stay zero).""" + off = np.asarray(offsets).reshape(-1).astype(np.int64) + last = off[1:] - 1 + return np.where(off[1:] > off[:-1], last, int(empty_row)).astype(np.uint32) + + +# ------------------------------------------------------------------------------------------------- oracles + +def _float_keys(a: np.ndarray) -> np.ndarray: + """float32 -> int32 keys whose signed order is the float order with -0 < +0 (an involution on the bits).""" + b = np.ascontiguousarray(a, np.float32).view(np.int32) + return b ^ ((b >> 31) & np.int32(0x7FFFFFFF)) + + +def _from_keys(k: np.ndarray) -> np.ndarray: + return (k ^ ((k >> 31) & np.int32(0x7FFFFFFF))).astype(np.int32).view(np.float32) + + +def segment_reduce_numpy(x: Any, offsets: Any, num_segments: Optional[int] = None, *, op: str = "max", + empty_value: float = 0.0) -> np.ndarray: + """Host oracle: ``out[s] = op(x[off[s]:off[s + 1]], axis=0)`` (``x`` ``[R, C]`` or ``[..., R, C]``), empty + segments -> ``empty_value``. ``max`` / ``min`` keep the input dtype (exact) and, for float32 / bf16-valued + inputs, order the floats as the K1 kernel does (signed zeros: ``-0 < +0``; numpy's ``maximum`` would keep + whichever zero comes first); ``sum`` / ``mean`` accumulate in float64 and return float32.""" + if op not in OPS: + raise ValueError(f"op {op!r}: one of {OPS}") + a = np.asarray(x) + a = a.reshape(-1, a.shape[-1]) + off = np.asarray(offsets).reshape(-1).astype(np.int64) + S = len(off) - 1 if num_segments is None else int(num_segments) + off = off[: S + 1] + out_dtype = a.dtype if op in ("max", "min") else np.float32 + out = np.full((S, a.shape[1]), empty_value, dtype=out_dtype) + nonempty = np.flatnonzero(off[1:] > off[:-1]) + if nonempty.size: + starts = off[:-1][nonempty] + if op in ("max", "min") and a.dtype == np.float32: + keys = _float_keys(a[: off[-1]]) + red = _from_keys((np.maximum if op == "max" else np.minimum).reduceat(keys, starts, axis=0)) + elif op in ("max", "min"): + red = (np.maximum if op == "max" else np.minimum).reduceat(a[: off[-1]], starts, axis=0) + else: + red = np.add.reduceat(a[: off[-1]].astype(np.float64), starts, axis=0) + if op == "mean": + red = red / (off[1:][nonempty] - starts)[:, None] + out[nonempty] = red.astype(out_dtype) + return out + + +def logstep_segment_max_numpy(x: Any, shift_tables: Sequence[Any], last_rows: Any) -> np.ndarray: + """Host twin of :func:`logstep_segment_max` (any dtype; exact): the rounds, then a gather of ``last_rows`` from + the result with one zero row appended (index ``R``: the empty segments).""" + a = np.asarray(x) + a = a.reshape(-1, a.shape[-1]) + for idx in shift_tables: + a = np.maximum(a, a[np.asarray(idx).reshape(-1).astype(np.int64)]) + a = np.concatenate([a, np.zeros((1, a.shape[1]), a.dtype)], axis=0) + return a[np.asarray(last_rows).reshape(-1).astype(np.int64)] + + +def worker_segments(offsets: Any, num_segments: int, num_workers: int, *, num_rows: Optional[int] = None + ) -> List[Tuple[int, int]]: + """The kernel's work split (host twin of ``segment_reduce_dm.cpp``): worker ``w`` owns the segments whose cost + ``off[s] + s`` lies in ``[w T / W, (w + 1) T / W)`` with ``T = off[S] + S`` -> ``[(s_lo, s_hi)]`` per worker. + Offsets are clamped to ``num_rows`` as the kernel clamps them.""" + off = np.asarray(offsets).reshape(-1).astype(np.int64)[: num_segments + 1] + if num_rows is not None: + off = np.minimum(off, int(num_rows)) + cost = off + np.arange(num_segments + 1) + total = int(cost[-1]) + out = [] + for w in range(num_workers): + t0 = (w * total) // num_workers + t1 = ((w + 1) * total) // num_workers + lo = 0 if w == 0 else int(np.searchsorted(cost, t0, side="left")) + hi = num_segments if w + 1 == num_workers else int(np.searchsorted(cost, t1, side="left")) + out.append((lo, max(lo, hi))) + return out + + +# ------------------------------------------------------------------------------------------------- device K1 + +def _f32_bits(value: float) -> int: + return int(np.array([value], np.float32).view(np.uint32)[0]) + + +@dataclass(frozen=True) +class SegmentReduceSpec: + """The static shape of one K1 call site (COMPILE): ``num_rows`` x ``channels`` input, ``num_segments`` outputs, + dtypes / layout, the empty value, and how many workers (data-movement RISC-Vs) per core run it.""" + + num_rows: int + channels: int + num_segments: int + input_dtype: str = "float32" # "float32" | "bfloat16" + input_layout: str = "tile" # "tile" | "row_major" + output_dtype: str = "float32" # "float32" | "bfloat16" (RNE) + op: str = "max" + empty_value: float = 0.0 + workers_per_core: int = 2 + unit_path: bool = True # 0.23.4: segments inside one 32-row unit reduced in registers (TILE input) + + def __post_init__(self) -> None: + if self.op not in DEVICE_OPS: + raise NotImplementedError(f"K1 runs {DEVICE_OPS} on the device; {self.op!r} is host-oracle only " + "(segment_reduce_numpy): sum / mean need float adds the data-movement RISC-Vs " + "do not have") + if self.num_rows <= 0 or self.num_rows % UNIT_ROWS: + raise ValueError(f"num_rows must be a positive multiple of {UNIT_ROWS}, got {self.num_rows}") + if self.channels <= 0 or self.channels % 32: + raise ValueError(f"channels must be a positive multiple of 32, got {self.channels}") + if self.num_segments <= 0: + raise ValueError("num_segments must be positive") + for name, value in (("input_dtype", self.input_dtype), ("output_dtype", self.output_dtype)): + if value not in ("float32", "bfloat16"): + raise ValueError(f"{name} {value!r}: 'float32' or 'bfloat16'") + if self.input_layout not in ("tile", "row_major"): + raise ValueError(f"input_layout {self.input_layout!r}: 'tile' or 'row_major'") + if self.workers_per_core not in (1, 2): + raise ValueError("workers_per_core must be 1 or 2") + if not np.isfinite(self.empty_value): + raise ValueError("empty_value must be finite") + + @property + def in_bytes(self) -> int: + return 4 if self.input_dtype == "float32" else 2 + + @property + def out_bytes(self) -> int: + return 4 if self.output_dtype == "float32" else 2 + + @property + def in_page_bytes(self) -> int: + return (1024 if self.input_layout == "tile" else self.channels) * self.in_bytes + + @property + def unit_bytes(self) -> int: + pages = self.channels // 32 if self.input_layout == "tile" else UNIT_ROWS + return pages * self.in_page_bytes + + @property + def out_row_bytes(self) -> int: + return self.channels * self.out_bytes + + def l1_bytes_per_worker(self) -> Dict[str, int]: + """The L1 scratch (CB) sizes of one worker: 2 data units, offsets window, probe block, accumulator, output + ring (each + 64 B so the kernel can align to the 64-byte DRAM read alignment).""" + return {"data": 2 * self.unit_bytes + 64, "offsets": _OFF_CHUNK * 4 + 64, "probe": 128, + "acc": self.channels * 4, "out": _OUT_RING * self.out_row_bytes + 64} + + def check_l1(self, budget: int = 600 * 1024) -> None: + """Refuse configurations whose per-core scratch exceeds ``budget`` (default 600 KiB of ~1.4 MiB).""" + per_core = self.workers_per_core * sum(self.l1_bytes_per_worker().values()) + if per_core > budget: + raise ValueError(f"K1 scratch {per_core} B per core exceeds {budget} B") + + +class SegmentReduce: + """K1 for one call site (static :class:`SegmentReduceSpec`). ``__call__(x, offsets, *, output=None)`` runs one + ``ttnn.generic_op`` (eagerly or inside a trace capture) and returns the ``[1, 1, num_segments, C]`` ROW_MAJOR + DRAM output (allocated per call unless ``output`` is given: a persistent buffer of that spec). + + ``x``: ``[1, 1, num_rows, C]`` interleaved DRAM tensor of the spec's dtype / layout, rows sorted by segment; + ``offsets``: uint32 ROW_MAJOR ``[1, K]`` DRAM (``K >= num_segments + 1``; :func:`check_offsets`), e.g. a + ``TraceRunner`` input rewritten per frame. The core grid is read from the device (never hard-coded); the split + across cores happens on the device, so ETH (12x10) and WORKER (11x10) runs give identical outputs.""" + + def __init__(self, spec: SegmentReduceSpec, *, name: str = "segment_reduce", grid: Optional[Tuple[int, int]] = None): + self.spec = spec + self.name = name + self.grid = grid # (x, y) cores; None = the device's compute grid + spec.check_l1() + + # ---- descriptor + def _grid(self, device: Any) -> Tuple[int, int]: + if self.grid is not None: + return int(self.grid[0]), int(self.grid[1]) + g = device.compute_with_storage_grid_size() + return int(g.x), int(g.y) + + def program(self, x: Any, offsets: Any, out: Any): + """The ``ttnn.ProgramDescriptor`` of one call (buffer addresses in common runtime args).""" + import ttnn + + spec = self.spec + gx, gy = self._grid(x.device()) + rect = ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(gx - 1, gy - 1)) + crs = ttnn.CoreRangeSet([rect]) + slots = spec.workers_per_core + workers = gx * gy * slots + off_len = int(offsets.shape[-1]) + sizes = spec.l1_bytes_per_worker() + cbs, kernels = [], [] + configs = [ttnn.WriterConfigDescriptor(), ttnn.ReaderConfigDescriptor()][:slots] + accessors = (list(ttnn.TensorAccessorArgs(x).get_compile_time_args()) + + list(ttnn.TensorAccessorArgs(offsets).get_compile_time_args()) + + list(ttnn.TensorAccessorArgs(out).get_compile_time_args())) + for slot, config in enumerate(configs): + ids = [5 * slot + k for k in range(5)] # data, offsets, probe, acc, out + for cb_id, size in zip(ids, (sizes["data"], sizes["offsets"], sizes["probe"], sizes["acc"], + sizes["out"])): + cbs.append(ttnn.CBDescriptor(total_size=size, core_ranges=crs, format_descriptors=[ + ttnn.CBFormatDescriptor(buffer_index=cb_id, data_format=ttnn.uint32, page_size=size)])) + ct = [1 if spec.input_layout == "tile" else 0, spec.in_bytes, spec.out_bytes, spec.channels, + spec.num_rows, spec.num_segments, workers, slots, slot, 0, 0, gx, *ids, _OUT_RING, _OFF_CHUNK, + _f32_bits(spec.empty_value), off_len * 4, int(bool(spec.unit_path))] + accessors + kernels.append(ttnn.KernelDescriptor( + kernel_source=kernel_path(KERNEL), source_type=ttnn.KernelDescriptor.SourceType.FILE_PATH, + core_ranges=crs, compile_time_args=ct, defines=[], runtime_args=ttnn.RuntimeArgs(), + common_runtime_args=[x.buffer_address(), offsets.buffer_address(), out.buffer_address()], + config=config)) + return ttnn.ProgramDescriptor(kernels=kernels, semaphores=[], cbs=cbs) + + # ---- checks + def _check_inputs(self, x: Any, offsets: Any) -> None: + import ttnn + + spec = self.spec + shape = tuple(int(s) for s in x.shape) + if shape != (1, 1, spec.num_rows, spec.channels): + raise ValueError(f"{self.name}: x is {shape}, expected (1, 1, {spec.num_rows}, {spec.channels})") + want_dtype = ttnn.float32 if spec.input_dtype == "float32" else ttnn.bfloat16 + if x.dtype != want_dtype: + raise ValueError(f"{self.name}: x dtype {x.dtype}, expected {spec.input_dtype}") + want_layout = ttnn.TILE_LAYOUT if spec.input_layout == "tile" else ttnn.ROW_MAJOR_LAYOUT + if x.layout != want_layout: + raise ValueError(f"{self.name}: x layout {x.layout}, expected {spec.input_layout}") + oshape = tuple(int(s) for s in offsets.shape) + if len(oshape) != 2 or oshape[0] != 1 or oshape[1] < spec.num_segments + 1: + raise ValueError(f"{self.name}: offsets must be [1, K >= {spec.num_segments + 1}], got {oshape}") + if offsets.dtype != ttnn.uint32 or offsets.layout != ttnn.ROW_MAJOR_LAYOUT: + raise ValueError(f"{self.name}: offsets must be uint32 ROW_MAJOR") + for t, what in ((x, "x"), (offsets, "offsets")): + mc = t.memory_config() + if getattr(mc, "buffer_type", ttnn.BufferType.DRAM) != ttnn.BufferType.DRAM or \ + getattr(mc, "memory_layout", ttnn.TensorMemoryLayout.INTERLEAVED) != \ + ttnn.TensorMemoryLayout.INTERLEAVED: + raise ValueError(f"{self.name}: {what} must be DRAM interleaved") + + def output_spec(self): + """``(shape, ttnn dtype, layout)`` of the output.""" + import ttnn + + dt = ttnn.float32 if self.spec.output_dtype == "float32" else ttnn.bfloat16 + return (1, 1, self.spec.num_segments, self.spec.channels), dt, ttnn.ROW_MAJOR_LAYOUT + + def allocate_output(self, device: Any): + import ttnn + + shape, dt, layout = self.output_spec() + return ttnn.allocate_tensor_on_device(ttnn.Shape(list(shape)), dt, layout, device, ttnn.DRAM_MEMORY_CONFIG) + + def __call__(self, x: Any, offsets: Any, *, output: Any = None): + import ttnn + + self._check_inputs(x, offsets) + out = self.allocate_output(x.device()) if output is None else output + shape, dt, layout = self.output_spec() + if tuple(int(s) for s in out.shape) != shape or out.dtype != dt or out.layout != layout: + raise ValueError(f"{self.name}: output must be {shape} {dt} ROW_MAJOR") + return ttnn.generic_op([x, offsets, out], self.program(x, offsets, out)) + + def describe(self) -> Dict[str, Any]: + s = self.spec + return {"name": self.name, "kernel": KERNEL, "op": s.op, "num_rows": s.num_rows, "channels": s.channels, + "num_segments": s.num_segments, "input": f"{s.input_dtype}/{s.input_layout}", + "output": f"{s.output_dtype}/row_major", "empty_value": s.empty_value, + "workers_per_core": s.workers_per_core, "grid": list(self.grid) if self.grid else "device", + "l1_bytes_per_worker": s.l1_bytes_per_worker()} + + +def segment_reduce(x: Any, offsets: Any, *, num_segments: int, op: str = "max", output_dtype: Optional[str] = None, + empty_value: float = 0.0, output: Any = None): + """One-shot K1 (builds a :class:`SegmentReduce` from the tensors; ports build it once per call site).""" + import ttnn + + in_dtype = "float32" if x.dtype == ttnn.float32 else "bfloat16" + spec = SegmentReduceSpec(num_rows=int(x.shape[-2]), channels=int(x.shape[-1]), num_segments=int(num_segments), + input_dtype=in_dtype, input_layout="tile" if x.layout == ttnn.TILE_LAYOUT else + "row_major", output_dtype=output_dtype or in_dtype, op=op, empty_value=empty_value) + return SegmentReduce(spec)(x, offsets, output=output) + + +# -------------------------------------------------------------------------------------- stock-op fallback + +def logstep_segment_max(x: Any, shift_tables: Sequence[Any], last_rows: Any, *, layout: str = "tile"): + """The exact log-step segmented max with stock ops (PLAN.md 1.3; the K1 fallback): ``x`` bf16 ``[1, 1, R, C]`` + (TILE or ROW_MAJOR, ``C % 32 == 0``), ``shift_tables`` = ``rounds`` uint32 ``[1, R]`` device tensors + (:func:`segment_shift_tables`), ``last_rows`` uint32 ``[1, S]`` (:func:`segment_last_rows` with ``empty_row=R``) + -> bf16 ``[1, 1, S, C]`` (``layout``). Per round: untilize, ``ttnn.embedding`` gather, ``ttnn.maximum`` (3 + programs); then one PADDED gather from the result with a zero row appended at ``R`` (empty segments -> 0). + bf16 only (``ttnn.embedding`` tables are bf16); exact for segments of up to ``2^rounds`` rows.""" + import ttnn + + from .gather import gather_rows, with_zero_rows + + if x.dtype != ttnn.bfloat16: + raise ValueError("logstep_segment_max is bf16-only (ttnn.embedding); use K1 (SegmentReduce) for fp32") + cur = x if x.layout == ttnn.TILE_LAYOUT else ttnn.to_layout(x, ttnn.TILE_LAYOUT) + for idx in shift_tables: + table = ttnn.to_layout(cur, ttnn.ROW_MAJOR_LAYOUT) + shifted = gather_rows(idx, table, layout="tile") + nxt = ttnn.maximum(cur, shifted) + for t in (table, shifted): + ttnn.deallocate(t, False) + if cur is not x: + ttnn.deallocate(cur, False) + cur = nxt + rows = int(cur.shape[-2]) + table = with_zero_rows(cur) # [1, 1, R + 1, C] ROW_MAJOR, row R = 0 + out = gather_rows(last_rows, table, sentinel=rows, layout=layout) + ttnn.deallocate(table, False) + if cur is not x: + ttnn.deallocate(cur, False) + return out diff --git a/code/tt_depthpro2/ttaw/ops/topk.py b/code/tt_depthpro2/ttaw/ops/topk.py new file mode 100644 index 0000000000000000000000000000000000000000..ca4994811f3226a6cb8ed71d07e69311e53828c9 --- /dev/null +++ b/code/tt_depthpro2/ttaw/ops/topk.py @@ -0,0 +1,293 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C21: top-k query selection on the device (PLAN.md section 1.2 row C21; probe P8, common/PROBES.md). + +The query-based LiDAR detectors (TransFusion, BEVFusion, PTv3) pick the ``K`` best (class, cell) proposals of a +local-max heatmap ``[C, H*W]``. On the p150 that is ``ttnn.experimental.topk_large_indices`` (Blackhole only): one +bf16 ROW_MAJOR row, ``k`` a multiple of 16 in [16, 2048], uint32 indices in descending value order, ~4.3 ns per +element on one core (0.71 / 0.80 / 1.98 ms over 162k / 184k / 459k values, P8). What the helpers here guarantee: + +- **The row is class-major** (:func:`class_major_row`): index ``c * cells + p`` for class ``c`` and cell ``p`` -- + the ONNX ``TopK`` order of a ``[1, C, H*W]`` reshape, so reference (teacher-forcing) indices need no conversion. + The NHWC heatmap ``[1, 1, cells, C]`` (TILE) is transposed (one program), reshaped to one row while still tiled, + and untilized: no ROW_MAJOR reshape of wide pages, whose L1 staging (2 x the destination page, API.md 13) would + not fit PT's 0.9 MB row (TF's is 0.37 MB). +- **Exact decode** (:func:`decode_class_major`): the uint32 indices are cast to fp32 (exact below 2**24) and decoded + with comparisons only, ``cls = sum_c (idx >= c * cells)``, ``pos = idx - cls * cells`` -- no division, so no + device rounding can move a boundary -- clamped into range (a 0xFFFFFFFF sentinel can never become an + out-of-range gather index) and cast back to uint32 ROW_MAJOR ``[1, K]`` rows (``ttnn.embedding`` indices). +- **Ties are unspecified** (P8: the device does not break ties by lowest index), so every gate after the selection + is set-based (:func:`selection_metrics`) or teacher-forced; the host oracle :func:`topk_numpy` has ONNX semantics + (stable descending: ties to the lower index). +- **Never ``-inf`` masks**: surviving ``-inf`` values come back as index 0xFFFFFFFF (P8); mask with + :data:`MASK_VALUE` (-1e30, finite in bf16) instead. +- ``k`` is padded to a multiple of 16 (:func:`padded_k`; 500 -> 512); keep the first ``K`` of the descending output. + +The bf16 ``ttnn.topk`` composite also returns the values (P8: +8-98 us, exact values): :func:`topk_with_values`. An +fp32 value re-gather costs ~1 us per index through ``ttnn.gather`` (P13); a two-stage top-k (row-split first stage) +is optimization work (PLAN.md 5.3). + +numpy only at import; ttnn is imported inside the device functions. +""" +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Sequence, Tuple + +import numpy as np + +__all__ = ["K_MULTIPLE", "K_MIN", "K_MAX", "MASK_VALUE", "SENTINEL", "padded_k", "class_major_row", "topk_indices", + "decode_class_major", "topk_with_values", "TopKSelect", "topk_numpy", "class_major_numpy", + "decode_class_major_numpy", "selection_metrics", "near_tie_report", "local_max_margins"] + +K_MULTIPLE = 16 +K_MIN = 16 +K_MAX = 2048 +MASK_VALUE = -1.0e30 # masking value for scores (never -inf: P8 sentinel) +SENTINEL = 0xFFFFFFFF # index returned for a surviving -inf +FP32_EXACT = 1 << 24 # integers below are exact in fp32 (the decode's range) + + +def padded_k(k: int) -> int: + """``k`` rounded up to the multiple of 16 ``topk_large_indices`` takes (500 -> 512); 16 <= result <= 2048.""" + k = int(k) + if k <= 0: + raise ValueError(f"k must be positive, got {k}") + kp = max(K_MIN, -(-k // K_MULTIPLE) * K_MULTIPLE) + if kp > K_MAX: + raise ValueError(f"k={k} exceeds topk_large_indices' maximum {K_MAX}") + return kp + + +# ------------------------------------------------------------------------------------------------- device + +def class_major_row(heat_nhwc: Any, classes: int, cells: int, *, memory_config: Any = None): + """NHWC heatmap ``[1, 1, cells, classes]`` (TILE, bf16) -> the class-major bf16 ROW_MAJOR row + ``[1, classes * cells]`` of the top-k (transpose, TILE reshape, untilize: traceable).""" + import ttnn + + shape = tuple(int(s) for s in heat_nhwc.shape) + if shape != (1, 1, int(cells), int(classes)): + raise ValueError(f"heat must be [1, 1, {cells}, {classes}], got {shape}") + if heat_nhwc.dtype != ttnn.bfloat16: + raise ValueError(f"topk_large_indices takes bf16 scores, got {heat_nhwc.dtype}") + kw = {} if memory_config is None else {"memory_config": memory_config} + n = int(classes) * int(cells) + t = ttnn.transpose(heat_nhwc, 2, 3, **kw) # [1, 1, classes, cells] TILE + flat = ttnn.reshape(t, (1, 1, 1, n)) # the row while still tiled (TILE reshape) + ttnn.deallocate(t, False) + rm = ttnn.to_layout(flat, ttnn.ROW_MAJOR_LAYOUT) # one row, untilized + ttnn.deallocate(flat, False) + return ttnn.reshape(rm, (1, n)) + + +def topk_indices(row: Any, k: int): + """``topk_large_indices`` of a bf16 ROW_MAJOR ``[rows, n]`` tensor -> uint32 ROW_MAJOR ``[rows, padded_k(k)]``, + descending (ties unspecified). Refuses an ``n`` beyond fp32's exact integers (the decode's range).""" + import ttnn + + n = int(row.shape[-1]) + kp = padded_k(k) + if n < kp: + raise ValueError(f"the row has {n} values, fewer than k={kp}") + if n > FP32_EXACT: + raise ValueError(f"row of {n} values: indices above 2**24 are not exact in the fp32 decode") + if row.dtype != ttnn.bfloat16 or row.layout != ttnn.ROW_MAJOR_LAYOUT: + raise ValueError("topk_large_indices takes a bf16 ROW_MAJOR row") + return ttnn.experimental.topk_large_indices(row, k=kp) + + +def decode_class_major(indices: Any, cells: int, classes: int, *, clamp: bool = True) -> Tuple[Any, Any]: + """Class-major flat indices (uint32, ROW_MAJOR ``[1, K]`` or TILE) -> ``(pos, cls)`` uint32 ROW_MAJOR ``[1, K]`` + with ``idx = cls * cells + pos`` (module docstring: fp32 comparisons, exact; ``clamp`` keeps them in range).""" + import ttnn + + cells, classes = int(cells), int(classes) + if cells * classes > FP32_EXACT: + raise ValueError("cells * classes exceeds fp32's exact integers") + it = indices if indices.layout == ttnn.TILE_LAYOUT else ttnn.to_layout(indices, ttnn.TILE_LAYOUT) + f = ttnn.typecast(it, ttnn.float32) + if it is not indices: + ttnn.deallocate(it, False) + cls = None + for c in range(1, classes): + ge = ttnn.ge(f, float(c * cells)) + if cls is None: + cls = ge + else: + s = ttnn.add(cls, ge) + ttnn.deallocate(cls, False) + ttnn.deallocate(ge, False) + cls = s + if cls is None: # one class: cls = 0, pos = idx + pos = f + cls = ttnn.multiply(f, 0.0) + else: + off = ttnn.multiply(cls, float(cells)) + pos = ttnn.subtract(f, off) + ttnn.deallocate(off, False) + ttnn.deallocate(f, False) + if clamp: + p2 = ttnn.clamp(pos, 0.0, float(cells - 1)) + c2 = ttnn.clamp(cls, 0.0, float(classes - 1)) + ttnn.deallocate(pos, False) + ttnn.deallocate(cls, False) + pos, cls = p2, c2 + out = [] + for t in (pos, cls): + u = ttnn.typecast(t, ttnn.uint32) + ttnn.deallocate(t, False) + r = ttnn.to_layout(u, ttnn.ROW_MAJOR_LAYOUT) + ttnn.deallocate(u, False) + out.append(r) + return out[0], out[1] + + +def topk_with_values(scores_tile: Any, k: int): + """The bf16 ``ttnn.topk`` composite on a TILE ``[.., n]`` row: ``(values bf16, indices)`` of the top ``k`` + (P8: exact values, in-range indices even with ``-inf``; ties unspecified).""" + import ttnn + + return ttnn.topk(scores_tile, k=int(k), dim=-1, largest=True, sorted=True) + + +class TopKSelect: + """Top-``k`` of a ``[1, 1, cells, classes]`` bf16 TILE heatmap -> uint32 class-major indices ``[1, padded_k]`` + (descending) plus the decoded ``(pos, cls)`` rows: :func:`class_major_row`, :func:`topk_indices`, + :func:`decode_class_major`. ``keep`` (default ``k``) proposals are meaningful; the rows hold ``padded_k(k)``.""" + + def __init__(self, cells: int, classes: int, k: int, *, name: str = "topk"): + self.cells, self.classes, self.k = int(cells), int(classes), int(k) + self.kp = padded_k(self.k) + if self.cells * self.classes < self.kp: + raise ValueError(f"{name}: {self.cells * self.classes} scores for k={self.kp}") + self.name = name + + def indices(self, heat_nhwc: Any): + row = class_major_row(heat_nhwc, self.classes, self.cells) + idx = topk_indices(row, self.kp) + import ttnn + + ttnn.deallocate(row, False) + return idx + + def decode(self, indices: Any) -> Tuple[Any, Any]: + return decode_class_major(indices, self.cells, self.classes) + + def __call__(self, heat_nhwc: Any) -> Tuple[Any, Any, Any]: + """-> ``(indices, pos, cls)``, each uint32 ROW_MAJOR ``[1, padded_k]``.""" + idx = self.indices(heat_nhwc) + pos, cls = self.decode(idx) + return idx, pos, cls + + def describe(self) -> Dict[str, Any]: + return {"name": self.name, "cells": self.cells, "classes": self.classes, "k": self.k, "padded_k": self.kp, + "order": "class-major (idx = cls * cells + pos)", "ties": "unspecified (P8)"} + + +# --------------------------------------------------------------------------------------------------- host + +def topk_numpy(scores: Any, k: int) -> Tuple[np.ndarray, np.ndarray]: + """ONNX ``TopK(largest=1, sorted=1)`` of a 1-D score vector: ``(values, indices)``, values descending, ties in + ascending index order (a stable descending sort).""" + s = np.asarray(scores).reshape(-1) + order = np.argsort(-s.astype(np.float64), kind="stable")[: int(k)] + return s[order], order.astype(np.int64) + + +def class_major_numpy(heat_nhwc: Any) -> np.ndarray: + """NHWC rows ``[cells, classes]`` -> the class-major flat vector of :func:`class_major_row`.""" + h = np.asarray(heat_nhwc) + return np.ascontiguousarray(h.reshape(-1, h.shape[-1]).T).reshape(-1) + + +def decode_class_major_numpy(indices: Any, cells: int) -> Tuple[np.ndarray, np.ndarray]: + """Host decode: ``(pos, cls)`` int64 of class-major flat indices.""" + i = np.asarray(indices).astype(np.int64).reshape(-1) + return i % int(cells), i // int(cells) + + +def selection_metrics(device_indices: Any, reference_indices: Any, *, reference_scores: Optional[Any] = None, + flat_scores: Optional[Any] = None, strong: float = 0.1, k: Optional[int] = None + ) -> Dict[str, Any]: + """Set-based agreement of a device top-k with the reference's (PLAN.md 2.5 / 0.3 item 1). + + ``device_indices`` / ``reference_indices``: flat indices (the first ``k`` of each are compared, default the + reference length). ``reference_scores``: the reference values of ``reference_indices`` (same order) or + ``flat_scores``: the reference score of every flat index. Returns ``shared`` (count) / ``shared_frac``, and with + scores the strong proposals (reference score >= ``strong``): ``strong_total``, ``strong_kept``, + ``strong_overlap`` (fraction; 1.0 when there is none), ``strong_missed`` (indices).""" + d = np.asarray(device_indices).astype(np.int64).reshape(-1) + r = np.asarray(reference_indices).astype(np.int64).reshape(-1) + k = len(r) if k is None else int(k) + d, r = d[:k], r[:k] + ds = set(d.tolist()) + out: Dict[str, Any] = {"k": k, "shared": len(ds & set(r.tolist())), "unique": len(ds) == len(d)} + out["device_only"] = sorted(ds - set(r.tolist())) + out["shared_frac"] = out["shared"] / max(k, 1) + if reference_scores is not None or flat_scores is not None: + if reference_scores is not None: + vals = np.asarray(reference_scores, np.float64).reshape(-1)[:k] + strong_set = set(r[vals >= strong].tolist()) + else: + fs = np.asarray(flat_scores, np.float64).reshape(-1) + strong_set = set(np.flatnonzero(fs >= strong).tolist()) + missed = sorted(strong_set - ds) + out.update({"strong_threshold": float(strong), "strong_total": len(strong_set), + "strong_kept": len(strong_set) - len(missed), + "strong_overlap": 1.0 if not strong_set else (len(strong_set) - len(missed)) / len(strong_set), + "strong_missed": missed}) + return out + + +def near_tie_report(missed: Sequence[int], device_indices: Any, reference_heat: Any, height: int, width: int, + *, kernel: int = 3) -> List[Dict[str, Any]]: + """Why a reference proposal is missing from a device selection (diagnostics of :func:`selection_metrics`). + + ``reference_heat``: the reference's class-major sigmoid heat BEFORE the local max (``[C * H * W]`` or + ``[C, H, W]``). For each missed class-major index: its heat, the strongest same-class cell of its ``kernel x + kernel`` window that the DEVICE selected, and the relative gap ``(heat_missed - heat_neighbour) / heat_missed`` + (a few 0.1 % = a local-max near-tie: the neighbour won the device's 3x3 comparison; a bf16 heat holds 3 + significant digits). ``neighbour`` is None when no same-class neighbour was selected.""" + heat = np.asarray(reference_heat, np.float64).reshape(-1) + cells = int(height) * int(width) + sel = set(np.asarray(device_indices).astype(np.int64).reshape(-1).tolist()) + r = int(kernel) // 2 + out: List[Dict[str, Any]] = [] + for idx in missed: + c, p = divmod(int(idx), cells) + y, x = divmod(p, int(width)) + best = None + for dy in range(-r, r + 1): + for dx in range(-r, r + 1): + yy, xx = y + dy, x + dx + if (dy or dx) and 0 <= yy < height and 0 <= xx < width: + q = c * cells + yy * int(width) + xx + if q in sel and (best is None or heat[q] > heat[best]): + best = q + rec: Dict[str, Any] = {"index": int(idx), "class": c, "cell": [y, x], "heat": float(heat[idx]), + "neighbour": None if best is None else int(best)} + if best is not None: + rec["neighbour_heat"] = float(heat[best]) + rec["relative_gap"] = float((heat[idx] - heat[best]) / max(heat[idx], 1e-30)) + out.append(rec) + return out + + +def local_max_margins(indices: Any, heat: Any, height: int, width: int, *, kernel: int = 3) -> np.ndarray: + """How decisive the reference's local-max decision is for each class-major proposal (the selection metric of a + "decisive" strong-proposal gate): ``(heat[p] - max_neighbour) / heat[p]`` over its same-class ``kernel x kernel`` + neighbours in ``heat`` (class-major ``[C * H * W]`` or ``[C, H, W]``, BEFORE the local max). A margin of at most + a few bf16 steps (0.39 % each) is a near-tie that a bf16 device heatmap cannot resolve; 1.0 for a cell without + neighbours. TransFusion gates the strong proposals with a margin above 0.5 % (``strong_overlap_decisive``) and + reports the rest with :func:`near_tie_report`.""" + hv = np.asarray(heat, np.float64).reshape(-1) + h, w = int(height), int(width) + cells = h * w + r = int(kernel) // 2 + out = [] + for idx in np.asarray(indices).astype(np.int64).reshape(-1): + c, p = divmod(int(idx), cells) + y, x = divmod(p, w) + nb = [hv[c * cells + yy * w + xx] for yy in range(y - r, y + r + 1) for xx in range(x - r, x + r + 1) + if (yy, xx) != (y, x) and 0 <= yy < h and 0 <= xx < w] + out.append((hv[idx] - max(nb)) / max(hv[idx], 1e-30) if nb else 1.0) + return np.asarray(out, np.float64) diff --git a/code/tt_depthpro2/ttaw/ops/upsample.py b/code/tt_depthpro2/ttaw/ops/upsample.py new file mode 100644 index 0000000000000000000000000000000000000000..f2bcf2bd7abcabc0a74921551394c0f02be0c6fe --- /dev/null +++ b/code/tt_depthpro2/ttaw/ops/upsample.py @@ -0,0 +1,319 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C18: up-sampling and interpolation helpers for NHWC feature maps (PLAN.md section 1.2 row C18). + +- :func:`upsample_nearest`: integer-factor nearest up-sampling through ``ttnn.upsample`` (floor indexing, exactly + ``F.interpolate(mode="nearest")`` and ONNX Resize nearest / asymmetric / floor: S:yolox section 4.3). ttnn's + nearest path takes ROW_MAJOR (interleaved or height / block sharded) or a TILE input whose W and C are multiples + of 32 (``upsample_common.cpp:25-65``) and always writes ROW_MAJOR, so the map goes TILE -> ROW_MAJOR -> + ``[N, H, W, C]`` -> upsample -> ``[1, 1, N*sH*H*sW*W, C]`` -> TILE (``output_layout``). Bit-exact (a data move). +- :func:`interp_matrix`: the 1-D interpolation matrix ``A [out, in]`` of ``F.interpolate`` (``"nearest"`` floor + rule, ``"linear"`` with ``align_corners`` True / False, the half-pixel rule clamped at 0 like torch), host numpy + float64. A 2-D resize is ``Y_c = A_h X_c A_w^T`` per channel (S:frnet:449, S:bevdet:488, S:meteor:497). +- :class:`Resize2d`: that separable resize on the device for any sizes (integer or not), e.g. the + ``align_corners=True`` bilinear of FRNet / BEVDet's FPN_LSS, which ``ttnn.upsample`` cannot do (its bilinear path + is half-pixel only, integer scales, sharded bf16 input). The W pass is a matmul over the transposed rows + (``[N*H, C, W] @ A_w^T``), the H pass ``A_h @ [H, W'*C]`` per image (``kron(I_N, A_h)`` for N > 1). Default + operands are float32 with HiFi4 + fp32 accumulation, because bf16 cannot hold weights such as 511/1023 (S:frnet:449) + and a device fp32 matmul is TF32-like (~1.5e-3 relative, probe P12); ``dtype="bfloat16"`` halves the traffic. + Static non-integer resizes may also use a precomputed ``grid_sample`` grid (probe P9: int16 corner indices exact, + bf16 weights; 1.7x faster than fp32 grids) through C23. + + **Tail (0.23.1).** The H pass leaves ``[1, 1, N*H', W'*C]``; the map wants ``[1, 1, N*H'*W', C]``. The original + ``tail="rm"`` goes TILE -> ROW_MAJOR -> ``reshape`` -> TILE. That ROW_MAJOR reshape turns W'*C-wide pages into + C-wide pages (e.g. 96,000 B -> 192 B): ttnn's dual-kernel RM reshape then writes small DRAM pages from both NOCs, + which **deadlocks a Blackhole p150 under ETH dispatch** within a few hundred traced replays (Blackhole SYS-1419; + ``logs/meteor/hangfix/ETH_DISPATCH_HANG_ISSUE.md``). ``tail="tile"`` reshapes the TILE tensor directly (no + ROW_MAJOR round trip; bit-identical, a data move; ~4-5 ms slower at METEOR's 800 x 48000). ``tail="auto"`` + (default) uses ``tile`` when the RM destination page (C x element size) is < :data:`RESIZE_TAIL_SAFE_PAGE_BYTES` + and the tt-metal tree lacks ``patches/tt-metal-reshape-rm-sys1419.patch`` (``ttaw.device.reshape_patch_present``; + 0.23.2), else ``rm`` (padded tiles included: bit-identical on the device for C 48 / 144 and odd row counts). With + the patch the RM reshape takes ttnn's single-kernel path, which is safe and faster (METEOR ETH trace 556.8 ms with + ``rm`` vs 594.7 ms with ``tile``). Environment override for A/B: + ``TTAW_RESIZE2D_TAIL=rm|tile|auto`` (read at construction). +""" +from __future__ import annotations + +from typing import Any, Dict, Optional, Sequence, Tuple, Union + +import numpy as np + +from ..precision import Precision +from ..tensors import dtype_name, ttnn_dtype +from .conv import FeatureMap, _layout, _memory_config + +__all__ = ["upsample_nearest", "interp_matrix", "resize_matrices", "Resize2d", "RESIZE_TAIL_SAFE_PAGE_BYTES", + "wpass_grid_config"] + +# Smallest ROW_MAJOR destination page (bytes) the Resize2d tail may reshape into on DRAM (module docstring, 0.23.1). +RESIZE_TAIL_SAFE_PAGE_BYTES = 4096 +_TAIL_MODES = ("auto", "rm", "tile") +_WPASS_MODES = ("batched", "flat", "grid") + + +def wpass_grid_config(batch_rows: int, channels: int, w_in: int, w_out: int, grid: Tuple[int, int]): + """0.24.1: the 1-D multicast program config of the batched W pass ``[1, B, C, W] x [W, W']`` with the batch fused + into M (``fuse_batch``: B * ceil(C / 32) tile rows, the padded per-batch rows included), split over every core + of ``grid`` (x, y), the broadcast ``A_w^T`` read whole by each core; ``in0_block_w`` the largest divisor of + Kt <= 4. Returns ``(in0_block_w, per_core_M, per_core_N, out_subblock_w)`` (host only, tests).""" + import math + + mt = int(batch_rows) * math.ceil(int(channels) / 32) + kt, nt = math.ceil(int(w_in) / 32), math.ceil(int(w_out) / 32) + ncores = int(grid[0]) * int(grid[1]) + k = max(d for d in (1, 2, 3, 4) if kt % d == 0) + sw = max(d for d in (1, 2, 4) if nt % d == 0) + return k, math.ceil(mt / ncores), nt, sw + + +def _pair(value: Union[int, Sequence[int]]) -> Tuple[int, int]: + if isinstance(value, (int, np.integer)): + return int(value), int(value) + a, b = (int(x) for x in value) + return a, b + + +def upsample_nearest(fm: FeatureMap, scale: Union[int, Sequence[int]] = 2, *, output_layout: Any = "tile", + memory_config: Any = "dram") -> FeatureMap: + """Nearest up-sampling by integer factors (bit-exact). Returns ``[1, 1, N*sH*H*sW*W, C]`` in + ``output_layout`` (TILE by default, what a following conv / concat wants).""" + import ttnn + + sh, sw = _pair(scale) + if sh < 1 or sw < 1: + raise ValueError(f"scale must be positive integers, got {scale!r}") + t = fm.tensor + if t.layout != ttnn.ROW_MAJOR_LAYOUT: + t = ttnn.to_layout(t, ttnn.ROW_MAJOR_LAYOUT) + t = ttnn.reshape(t, (fm.batch, fm.height, fm.width, fm.channels)) + up = ttnn.upsample(t, (sh, sw), mode="nearest", memory_config=_memory_config(memory_config)) + out = ttnn.reshape(up, (1, 1, fm.batch * fm.height * sh * fm.width * sw, fm.channels)) + if _layout(output_layout) == ttnn.TILE_LAYOUT: + out = ttnn.to_layout(out, ttnn.TILE_LAYOUT) + return FeatureMap(out, fm.batch, fm.height * sh, fm.width * sw, fm.channels) + + +def interp_matrix(in_size: int, out_size: int, *, mode: str = "linear", align_corners: bool = False, + scale: Optional[float] = None) -> np.ndarray: + """``A`` (float64, ``[out_size, in_size]``) with ``y = A @ x`` equal to 1-D ``F.interpolate`` of ``x``. + + ``mode``: ``"nearest"`` (``src = min(floor(dst * s), in - 1)``) or ``"linear"`` (``align_corners=True``: + ``src = dst * (in - 1) / (out - 1)``; False: ``src = max((dst + 0.5) * s - 0.5, 0)``). ``s`` is ``in / out``, + or ``1 / scale`` when the caller passed ``scale_factor=scale`` to torch (its default + ``recompute_scale_factor=None`` keeps the given factor).""" + if in_size < 1 or out_size < 1: + raise ValueError(f"sizes must be positive, got {in_size} -> {out_size}") + s = (1.0 / float(scale)) if scale is not None else in_size / out_size + dst = np.arange(out_size, dtype=np.float64) + a = np.zeros((out_size, in_size), np.float64) + rows = np.arange(out_size) + if mode == "nearest": + if align_corners: + raise ValueError("align_corners applies to linear modes only") + # torch's nearest_idx: floorf(dst * (float)scale) in float32 (the exact 2x case equals dst >> 1) + prod = (dst.astype(np.float32) * np.float32(s)).astype(np.float32) + src = np.minimum(np.floor(prod).astype(np.int64), in_size - 1) + a[rows, src] = 1.0 + return a + if mode != "linear": + raise ValueError(f"mode {mode!r}: expected 'nearest' or 'linear'") + if align_corners: + src = dst * ((in_size - 1) / (out_size - 1)) if out_size > 1 else np.zeros(out_size) + else: + src = np.maximum((dst + 0.5) * s - 0.5, 0.0) + i0 = np.minimum(np.floor(src).astype(np.int64), in_size - 1) + i1 = np.minimum(i0 + 1, in_size - 1) + lam = src - i0 + np.add.at(a, (rows, i0), 1.0 - lam) + np.add.at(a, (rows, i1), lam) + return a + + +def resize_matrices(in_hw: Tuple[int, int], out_hw: Tuple[int, int], *, mode: str = "linear", + align_corners: bool = False, scale: Optional[Union[float, Sequence[float]]] = None + ) -> Tuple[np.ndarray, np.ndarray]: + """``(A_h [H', H], A_w [W', W])`` of a 2-D resize: ``Y_c = A_h @ X_c @ A_w.T``.""" + sh, sw = (None, None) if scale is None else (_pair_f(scale)) + return (interp_matrix(in_hw[0], out_hw[0], mode=mode, align_corners=align_corners, scale=sh), + interp_matrix(in_hw[1], out_hw[1], mode=mode, align_corners=align_corners, scale=sw)) + + +def _pair_f(value: Union[float, Sequence[float]]) -> Tuple[float, float]: + if isinstance(value, (int, float, np.floating, np.integer)): + return float(value), float(value) + a, b = (float(x) for x in value) + return a, b + + +class Resize2d: + """Separable 2-D resize of an NHWC feature map on the device (see the module docstring). + + Args: + in_hw, out_hw: input / output spatial size. ``channels``, ``batch``: map size (static: one instance per + call site). + mode, align_corners, scale: as :func:`interp_matrix`. + dtype: operand dtype of the two matmuls (``"float32"`` default; the input is typecast, the output cast + back to ``output_dtype``). + precision: compute config of the matmuls (``"accurate"``: HiFi4 + fp32 accumulation; never LoFi for fp32 + operands, probe P12). + Matrices are uploaded on the first call (warm-up), never inside a capture.""" + + def __init__(self, in_hw: Tuple[int, int], out_hw: Tuple[int, int], *, channels: int, batch: int = 1, + mode: str = "linear", align_corners: bool = False, scale: Optional[Any] = None, + dtype: Any = "float32", output_dtype: Any = "bfloat16", precision: Any = "accurate", + output_layout: Any = "tile", tail: str = "auto", w_pass: str = "batched", rerow: str = "stock", + name: str = "resize"): + import os + + from .rerow import REROW_MODES + + self.name = name + rerow = (os.environ.get("TTAW_RESIZE2D_REROW") or rerow).strip().lower() + if rerow not in REROW_MODES: + raise ValueError(f"{name}: rerow={rerow!r}: expected one of {REROW_MODES}") + # 0.24.0: "kernel" runs the rm tail's ROW_MAJOR page re-cut [N*H', W'*C] -> [N*H'*W', C] as the K12 rerow + # page copy (ops/rerow.py) instead of ttnn's RM reshape (bit-identical, 2x faster at METEOR's shapes); the + # H-pass input join [N*H*W', C] -> [N*H, W'*C] stays ttnn's (faster for joins). + self.rerow = rerow + w_pass = (os.environ.get("TTAW_RESIZE2D_WPASS") or w_pass).strip().lower() + if w_pass not in _WPASS_MODES: + raise ValueError(f"{name}: w_pass={w_pass!r}: expected one of {_WPASS_MODES}") + # 0.23.5: "flat" runs the W pass as ONE 2-D matmul [N*H*C, W] x [W, W'] (the transposed rows viewed flat, + # a view when C % 32 == 0) instead of a batched [1, N*H, C, W] x [W, W'] matmul, which ttnn places on + # N*H*C/32 x W'/32 output blocks of few cores (METEOR: 16-24 cores, 2.9 ms at 400x96x250 -> 500). Falls + # back to "batched" when C % 32 != 0. + # 0.24.1: "grid" = "flat" where C % 32 == 0, else the batched pass with an explicit 1-D program config that + # fuses the batch into M over the device grid (wpass_grid_config; METEOR's 48-channel seg resize: 16 cores + # 2.95 ms -> 120 cores 0.41 ms, bit-identical); a config ttnn refuses on the first (eager) call falls back to + # ttnn's own for the layer's lifetime. + self.w_pass_request = w_pass + if int(channels) % 32 == 0 and w_pass in ("flat", "grid"): + self.w_pass = "flat" + else: + self.w_pass = "grid" if w_pass == "grid" else "batched" + self._grid_pc: Any = None + tail = (os.environ.get("TTAW_RESIZE2D_TAIL") or tail).strip().lower() + if tail not in _TAIL_MODES: + raise ValueError(f"{name}: tail={tail!r}: expected one of {_TAIL_MODES}") + self.tail_request = tail + self.in_hw = (int(in_hw[0]), int(in_hw[1])) + self.out_hw = (int(out_hw[0]), int(out_hw[1])) + self.channels, self.batch = int(channels), int(batch) + self.mode, self.align_corners = mode, bool(align_corners) + self.a_h, self.a_w = resize_matrices(self.in_hw, self.out_hw, mode=mode, align_corners=align_corners, + scale=scale) + self.dtype = dtype_name(dtype) + self.output_dtype = dtype_name(output_dtype) + self.precision = Precision.parse(precision) + self.output_layout = output_layout + self._dev: Optional[Tuple[Any, Any]] = None + self.tail = self._resolve_tail(tail) + + def _resolve_tail(self, tail: str) -> str: + """``auto`` -> ``tile`` when the ROW_MAJOR tail would write small DRAM pages (module docstring), else ``rm``.""" + if tail != "auto": + return tail + from ..device import reshape_patch_present + + elem = 4 if self.output_dtype in ("float32", "uint32", "int32") else 2 + if self.channels * elem >= RESIZE_TAIL_SAFE_PAGE_BYTES: + return "rm" + # small pages: safe as ROW_MAJOR only on a tt-metal with the reshape patch (single kernel; ~5x faster than the + # TILE reshape at METEOR's lift shape), else the TILE tail + return "rm" if reshape_patch_present(min_page_bytes=RESIZE_TAIL_SAFE_PAGE_BYTES) else "tile" + + def host_matrices(self) -> Tuple[np.ndarray, np.ndarray]: + """The device operands: ``A_w^T [W, W']`` and ``kron(I_N, A_h) [N*H', N*H]`` (float32).""" + aw_t = np.ascontiguousarray(self.a_w.T, np.float32) + ah = self.a_h if self.batch == 1 else np.kron(np.eye(self.batch), self.a_h) + return aw_t, np.ascontiguousarray(ah, np.float32) + + def reference(self, nchw: np.ndarray) -> np.ndarray: + """Host float64 result of the same matrices (tests).""" + x = np.asarray(nchw, np.float64) + return np.einsum("ph,nchw,qw->ncpq", self.a_h, x, self.a_w) + + def __call__(self, fm: FeatureMap) -> FeatureMap: + import torch + import ttnn + + from .rerow import rerow as _rerow + + n, (h, w), c = self.batch, self.in_hw, self.channels + (h2, w2) = self.out_hw + if (fm.batch, fm.height, fm.width, fm.channels) != (n, h, w, c): + got = (fm.batch, fm.height, fm.width, fm.channels) + raise ValueError(f"{self.name}: built for {(n, h, w, c)}, got {got}") + dt = ttnn_dtype(self.dtype) + cfg = self.precision.compute_kernel_config() + if self._dev is None: + aw_t, ah = self.host_matrices() + dev = fm.tensor.device() + self._dev = (ttnn.from_torch(torch.from_numpy(aw_t), dtype=dt, layout=ttnn.TILE_LAYOUT, device=dev), + ttnn.from_torch(torch.from_numpy(ah), dtype=dt, layout=ttnn.TILE_LAYOUT, device=dev)) + aw_t_dev, ah_dev = self._dev + x = fm.tensor + if x.layout != ttnn.ROW_MAJOR_LAYOUT: + x = ttnn.to_layout(x, ttnn.ROW_MAJOR_LAYOUT) + x = ttnn.reshape(x, (1, n * h, w, c)) + x = ttnn.to_layout(x, ttnn.TILE_LAYOUT) + if x.dtype != dt: + x = ttnn.typecast(x, dt) + xt = ttnn.transpose(x, -2, -1) # [1, N*H, C, W] + if self.w_pass == "flat": # a view: C % 32 == 0 + y = ttnn.matmul(ttnn.reshape(xt, (1, 1, n * h * c, w)), aw_t_dev, compute_kernel_config=cfg) + y = ttnn.reshape(y, (1, n * h, c, w2)) + elif self.w_pass == "grid" and self._grid_pc is not False: + y = self._grid_matmul(xt, aw_t_dev, cfg, n * h, c, w, w2) # [1, N*H, C, W'] over the grid + else: + y = ttnn.matmul(xt, aw_t_dev, compute_kernel_config=cfg) # [1, N*H, C, W'] + y = ttnn.transpose(y, -2, -1) # [1, N*H, W', C] + y = ttnn.to_layout(y, ttnn.ROW_MAJOR_LAYOUT) + y = _rerow(y, (1, 1, n * h, w2 * c), mode=self.rerow) + y = ttnn.to_layout(y, ttnn.TILE_LAYOUT) + z = ttnn.matmul(ah_dev, y, compute_kernel_config=cfg) # [1, 1, N*H', W'*C] + if z.dtype != ttnn_dtype(self.output_dtype): + z = ttnn.typecast(z, ttnn_dtype(self.output_dtype)) # TILE typecast (every dtype pair) + if self.tail == "tile": # TILE reshape: no small RM DRAM pages + z = ttnn.reshape(z, (1, 1, n * h2 * w2, c)) + if _layout(self.output_layout) != ttnn.TILE_LAYOUT: + z = ttnn.to_layout(z, ttnn.ROW_MAJOR_LAYOUT) + return FeatureMap(z, n, h2, w2, c) + z = ttnn.to_layout(z, ttnn.ROW_MAJOR_LAYOUT) + z = _rerow(z, (1, 1, n * h2 * w2, c), mode=self.rerow) + if _layout(self.output_layout) == ttnn.TILE_LAYOUT: + z = ttnn.to_layout(z, ttnn.TILE_LAYOUT) + return FeatureMap(z, n, h2, w2, c) + + def _grid_matmul(self, xt: Any, aw_t_dev: Any, cfg: Any, rows: int, c: int, w: int, w2: int) -> Any: + """The batched W pass with :func:`wpass_grid_config` (``w_pass="grid"``, C % 32 != 0); ttnn's own config + when the explicit one is refused (decided on the first, eager call).""" + import ttnn + + if self._grid_pc is None: + g = xt.device().compute_with_storage_grid_size() + k, pm, pn, sw = wpass_grid_config(rows, c, w, w2, (int(g.x), int(g.y))) + pc = ttnn.MatmulMultiCoreReuseMultiCast1DProgramConfig( + compute_with_storage_grid_size=ttnn.CoreCoord(int(g.x), int(g.y)), in0_block_w=k, out_subblock_h=1, + out_subblock_w=sw, per_core_M=pm, per_core_N=pn, fuse_batch=True, fused_activation=None, + mcast_in0=False) + try: + y = ttnn.matmul(xt, aw_t_dev, compute_kernel_config=cfg, program_config=pc) + except RuntimeError: + self._grid_pc = False + return ttnn.matmul(xt, aw_t_dev, compute_kernel_config=cfg) + self._grid_pc = pc + return y + return ttnn.matmul(xt, aw_t_dev, compute_kernel_config=cfg, program_config=self._grid_pc) + + def release(self) -> None: + import ttnn + + for t in self._dev or (): + if t.is_allocated(): + ttnn.deallocate(t) + self._dev = None + + def describe(self) -> Dict[str, Any]: + return {"name": self.name, "in_hw": list(self.in_hw), "out_hw": list(self.out_hw), "channels": self.channels, + "batch": self.batch, "mode": self.mode, "align_corners": self.align_corners, "dtype": self.dtype, + "tail": self.tail, "w_pass": self.w_pass, "rerow": self.rerow} diff --git a/code/tt_depthpro2/ttaw/outputs.py b/code/tt_depthpro2/ttaw/outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..34e3c034edce2da9e38c88516edce8994ac222c8 --- /dev/null +++ b/code/tt_depthpro2/ttaw/outputs.py @@ -0,0 +1,283 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C08 outputs: the result classes of the 13 bundles and their ``POST /predict`` JSON (BUNDLE_CONVENTIONS.md 7.4). + +Every class has ``to_dicts()`` (one plain dict per detection / pose / class) and ``to_dict(output_format)`` (the +whole response body: ``model``, ``frame_id``, the payload, ``meta``, ``timing_ms``). The Python API returns these +objects and the server returns ``to_dict(...)`` of the same object, so both agree bit for bit. + +================== ================================= ================================================== +class families payload +================== ================================= ================================================== +``Detections3D`` CenterPoint, TransFusion, BEVFusion, ``detections`` [label, label_id, score, center, size, + PointPainting, StreamPETR, BEVDet, yaw, velocity], ``num_detections``; rows sorted by + BEVFormer, PTv3-det descending score at construction +``Detections2D`` YOLOX ``detections`` [label, label_id, score, box_xyxy] + + ``extras`` (e.g. ``{"semseg": Mask2D}``) +``Segmentation3D`` FRNet, PTv3-seg ``labels`` (npz uint8/uint16 [N]), ``scores``, + ``class_names``, ``class_counts`` +``Mask2D`` SceneSeg (YOLOX semseg extra) ``mask`` (png or npz), ``class_names``, ``class_counts`` +``Trajectory`` Diffusion Planner ``trajectory`` [[x, y, yaw, ...] x T], ``columns``, + ``turn_indicator``, ``predicted_agents`` +================== ================================= ================================================== +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Sequence + +import numpy as np + +from .io import encode_array, encode_png, to_jsonable + +__all__ = ["Detections3D", "Detections2D", "Segmentation3D", "Mask2D", "Trajectory", "label_name"] + + +def label_name(labels: Sequence[str], label_id: int) -> str: + """``labels[label_id]``, or the id as text when it is out of range.""" + return labels[label_id] if 0 <= label_id < len(labels) else str(label_id) + + +def _envelope(model: str, frame_id: str, meta: dict, timing_ms: dict) -> Dict[str, Any]: + return {"model": model, "frame_id": frame_id, "meta": to_jsonable(meta), + "timing_ms": {k: round(float(v), 3) for k, v in timing_ms.items()}} + + +def _sorted_by_score(scores: np.ndarray) -> np.ndarray: + return np.argsort(-scores, kind="stable") + + +@dataclass +class Detections3D: + """3D boxes in ``frame_id`` (Autoware ``base_link``: x forward, y left, z up; metres, radians). + + ``boxes`` float32 ``[N, 7]`` = x, y, z (box centre), length, width, height, yaw; ``scores`` ``[N]``; + ``label_ids`` int32 ``[N]`` (index into ``labels``); ``velocities`` ``[N, 2]`` (vx, vy) m/s or None. + Rows are sorted by descending score (stable) at construction.""" + + boxes: np.ndarray + scores: np.ndarray + label_ids: np.ndarray + velocities: Optional[np.ndarray] = None + labels: Sequence[str] = () + model: str = "" + frame_id: str = "base_link" + timing_ms: dict = field(default_factory=dict) + meta: dict = field(default_factory=dict) + + def __post_init__(self) -> None: + self.boxes = np.asarray(self.boxes, np.float32).reshape(-1, 7) + self.scores = np.asarray(self.scores, np.float32).reshape(-1) + self.label_ids = np.asarray(self.label_ids, np.int32).reshape(-1) + n = len(self.scores) + if len(self.boxes) != n or len(self.label_ids) != n: + raise ValueError(f"boxes {self.boxes.shape}, scores {self.scores.shape}, labels {self.label_ids.shape}") + if self.velocities is not None: + self.velocities = np.asarray(self.velocities, np.float32).reshape(n, 2) + order = _sorted_by_score(self.scores) + self.boxes, self.scores, self.label_ids = self.boxes[order], self.scores[order], self.label_ids[order] + if self.velocities is not None: + self.velocities = self.velocities[order] + + def __len__(self) -> int: + return int(self.scores.shape[0]) + + @property + def label_names(self) -> List[str]: + return [label_name(self.labels, i) for i in self.label_ids.tolist()] + + def to_dicts(self) -> List[Dict[str, Any]]: + out = [] + for i, name in enumerate(self.label_names): + x, y, z, length, width, height, yaw = (float(v) for v in self.boxes[i]) + d = {"label": name, "label_id": int(self.label_ids[i]), "score": round(float(self.scores[i]), 4), + "center": [round(x, 3), round(y, 3), round(z, 3)], + "size": [round(length, 3), round(width, 3), round(height, 3)], "yaw": round(yaw, 4)} + if self.velocities is not None: + d["velocity"] = [round(float(v), 3) for v in self.velocities[i]] + out.append(d) + return out + + def to_dict(self, output_format: str = "json") -> Dict[str, Any]: + body = _envelope(self.model, self.frame_id, self.meta, self.timing_ms) + body.update(num_detections=len(self), detections=self.to_dicts()) + if output_format == "npz": # lossless arrays for programmatic clients + body["arrays"] = {"boxes": encode_array(self.boxes, key="boxes"), + "scores": encode_array(self.scores, key="scores"), + "label_ids": encode_array(self.label_ids, key="label_ids")} + if self.velocities is not None: + body["arrays"]["velocities"] = encode_array(self.velocities, key="velocities") + return body + + +@dataclass +class Mask2D: + """A per-pixel class map (H, W) (uint8 for <= 256 classes) in the source image's pixel grid.""" + + mask: np.ndarray + class_names: Sequence[str] = () + model: str = "" + frame_id: str = "camera" + encoding: str = "png" + timing_ms: dict = field(default_factory=dict) + meta: dict = field(default_factory=dict) + + def __post_init__(self) -> None: + self.mask = np.asarray(self.mask) + if self.mask.ndim != 2: + raise ValueError(f"mask must be (H, W), got {self.mask.shape}") + if self.encoding not in ("png", "npz"): + raise ValueError("encoding must be 'png' or 'npz'") + + def class_counts(self) -> Dict[str, int]: + ids, counts = np.unique(self.mask, return_counts=True) + return {label_name(self.class_names, int(i)): int(c) for i, c in zip(ids, counts)} + + def to_dicts(self) -> List[Dict[str, Any]]: + ids, counts = np.unique(self.mask, return_counts=True) + return [{"label": label_name(self.class_names, int(i)), "label_id": int(i), "pixels": int(c)} + for i, c in zip(ids, counts)] + + def payload(self, output_format: str = "json") -> Dict[str, Any]: + """The encoded mask alone (also used when the mask is an extra of another output).""" + if self.encoding == "png" and output_format != "npz" and self.mask.dtype == np.uint8: + return encode_png(self.mask, key="mask") + return encode_array(self.mask, key="mask") + + def to_dict(self, output_format: str = "json") -> Dict[str, Any]: + body = _envelope(self.model, self.frame_id, self.meta, self.timing_ms) + body.update(mask=self.payload(output_format), class_names=list(self.class_names), + class_counts=self.class_counts()) + return body + + +@dataclass +class Detections2D: + """2-D boxes in original image pixels: ``boxes_xyxy`` float32 ``[N, 4]``, ``scores``, ``label_ids``. + ``extras`` holds companion outputs encoded into the body by name (``{"semseg": Mask2D(...)}``). + Rows are sorted by descending score (stable) at construction.""" + + boxes_xyxy: np.ndarray + scores: np.ndarray + label_ids: np.ndarray + labels: Sequence[str] = () + extras: Dict[str, Any] = field(default_factory=dict) + model: str = "" + frame_id: str = "camera" + timing_ms: dict = field(default_factory=dict) + meta: dict = field(default_factory=dict) + + def __post_init__(self) -> None: + self.boxes_xyxy = np.asarray(self.boxes_xyxy, np.float32).reshape(-1, 4) + self.scores = np.asarray(self.scores, np.float32).reshape(-1) + self.label_ids = np.asarray(self.label_ids, np.int32).reshape(-1) + if not (len(self.boxes_xyxy) == len(self.scores) == len(self.label_ids)): + raise ValueError("boxes_xyxy, scores and label_ids lengths differ") + order = _sorted_by_score(self.scores) + self.boxes_xyxy, self.scores, self.label_ids = self.boxes_xyxy[order], self.scores[order], self.label_ids[order] + + def __len__(self) -> int: + return int(self.scores.shape[0]) + + def to_dicts(self) -> List[Dict[str, Any]]: + return [{"label": label_name(self.labels, int(self.label_ids[i])), "label_id": int(self.label_ids[i]), + "score": round(float(self.scores[i]), 4), + "box_xyxy": [round(float(v), 2) for v in self.boxes_xyxy[i]]} for i in range(len(self))] + + def to_dict(self, output_format: str = "json") -> Dict[str, Any]: + body = _envelope(self.model, self.frame_id, self.meta, self.timing_ms) + body.update(num_detections=len(self), detections=self.to_dicts()) + for name, extra in self.extras.items(): + if hasattr(extra, "payload"): + body[name] = extra.payload(output_format) + elif isinstance(extra, np.ndarray): + body[name] = encode_array(extra, key=name) + else: + body[name] = to_jsonable(extra) + if output_format == "npz": + body["arrays"] = {"boxes_xyxy": encode_array(self.boxes_xyxy, key="boxes_xyxy"), + "scores": encode_array(self.scores, key="scores"), + "label_ids": encode_array(self.label_ids, key="label_ids")} + return body + + +@dataclass +class Segmentation3D: + """Per-point classes, in input point order after NaN removal (stated in SERVING.md). ``label_ids`` ``[N]``; + ``scores`` optional ``[N]`` (winning-class probability) or ``[N, C]``.""" + + label_ids: np.ndarray + class_names: Sequence[str] = () + scores: Optional[np.ndarray] = None + model: str = "" + frame_id: str = "base_link" + timing_ms: dict = field(default_factory=dict) + meta: dict = field(default_factory=dict) + + def __post_init__(self) -> None: + ids = np.asarray(self.label_ids).reshape(-1) + if ids.size and ids.min() < 0: + raise ValueError("label ids must be >= 0") + self.label_ids = ids.astype(np.uint8 if (not ids.size or ids.max() < 256) else np.uint16) + if self.scores is not None: + self.scores = np.asarray(self.scores, np.float32) + if self.scores.shape[0] != ids.shape[0]: + raise ValueError("scores and label_ids lengths differ") + + def __len__(self) -> int: + return int(self.label_ids.shape[0]) + + def class_counts(self) -> Dict[str, int]: + counts = np.bincount(self.label_ids.astype(np.int64), minlength=len(self.class_names)) + return {label_name(self.class_names, i): int(c) for i, c in enumerate(counts) if c or i < len(self.class_names)} + + def to_dicts(self) -> List[Dict[str, Any]]: + counts = np.bincount(self.label_ids.astype(np.int64), minlength=len(self.class_names)) + return [{"label": label_name(self.class_names, i), "label_id": i, "points": int(c)} + for i, c in enumerate(counts)] + + def to_dict(self, output_format: str = "json") -> Dict[str, Any]: + body = _envelope(self.model, self.frame_id, self.meta, self.timing_ms) + body.update(num_points=len(self), labels=encode_array(self.label_ids, key="labels"), + class_names=list(self.class_names), class_counts=self.class_counts()) + if self.scores is not None: + body["scores"] = encode_array(self.scores, key="scores") + return body + + +@dataclass +class Trajectory: + """A planned trajectory ``poses`` ``[T, D]`` whose columns are named by ``columns`` (default x, y, yaw) in + ``frame_id``; optional ``turn_indicator`` and ``predicted_agents`` ``[A, T, D']``.""" + + poses: np.ndarray + columns: Sequence[str] = ("x", "y", "yaw") + turn_indicator: Any = None + predicted_agents: Optional[np.ndarray] = None + model: str = "" + frame_id: str = "base_link" + timing_ms: dict = field(default_factory=dict) + meta: dict = field(default_factory=dict) + + def __post_init__(self) -> None: + self.poses = np.asarray(self.poses, np.float32) + if self.poses.ndim != 2 or self.poses.shape[1] != len(self.columns): + raise ValueError(f"poses {self.poses.shape} do not match columns {list(self.columns)}") + if self.predicted_agents is not None: + self.predicted_agents = np.asarray(self.predicted_agents, np.float32) + + def __len__(self) -> int: + return int(self.poses.shape[0]) + + def to_dicts(self) -> List[Dict[str, Any]]: + return [{c: round(float(v), 4) for c, v in zip(self.columns, row)} for row in self.poses] + + def to_dict(self, output_format: str = "json") -> Dict[str, Any]: + body = _envelope(self.model, self.frame_id, self.meta, self.timing_ms) + body.update(num_poses=len(self), columns=list(self.columns), + trajectory=[[round(float(v), 4) for v in row] for row in self.poses], + turn_indicator=to_jsonable(self.turn_indicator)) + if self.predicted_agents is not None: + body["predicted_agents"] = encode_array(self.predicted_agents, key="predicted_agents") + if output_format == "npz": + body["arrays"] = {"poses": encode_array(self.poses, key="poses")} + return body diff --git a/code/tt_depthpro2/ttaw/pointcloud.py b/code/tt_depthpro2/ttaw/pointcloud.py new file mode 100644 index 0000000000000000000000000000000000000000..9d94aa12a3a017517b2a49cd4c7c6183cae1bd45 --- /dev/null +++ b/code/tt_depthpro2/ttaw/pointcloud.py @@ -0,0 +1,282 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C11 point clouds: Autoware's multi-sweep densification state machine, input hygiene and the seeded permutation. + +**Densification** (``PointCloudDensification`` + ``VoxelGenerator::generateSweepPoints`` of +``autoware_lidar_centerpoint``; the same code shape is in lidar_transfusion, bevfusion and +image_projection_based_fusion: S:centerpoint:164-176; S:transfusion:99-103; S:pointpainting:216-221): + +- a cache holds the current cloud and ``num_past_frames`` previous ones, newest first (``push_front`` / + ``pop_back``, ``pointcloud_densification.cpp:79-95``); +- with a cache size > 1 every enqueue needs the TF ``T_sensor_from_world`` at the cloud's stamp; when it is missing + the frame is **skipped and not cached** (``:66-71``). The node keeps the world->current transform and each entry's + past->world transform as ``Eigen::Affine3f`` (float32, inverted in float32: ``:47-51,82-86``); +- at the end of each frame every cached cloud is re-transformed with ``world2current(now) @ past2world(entry)`` + (float32 product) by the float32 CUDA kernel, and gets ``time_lag = float(t_now - t_entry)`` in seconds + (``voxel_generator.cpp:56-93``). There is no maximum-age check: after dropped frames the past sweep can be old; +- points are written current sweep first; a sweep that would exceed ``cloud_capacity`` is dropped **with every older + sweep** (``voxel_generator.cpp:70-76``, a ``break``); +- cold start: the first frame has a single sweep (all ``time_lag = 0``); ``num_past_frames = 0`` needs no TF at all. + +:class:`SweepDensifier` is that state machine for one stream, :class:`StreamDensifiers` a per-``stream.id`` dict with +LRU eviction (PLAN.md D16: host sweep caches are per id), and :func:`densify_sweeps` the stateless variant for a +client that sends its past sweeps with ``T_current_from_sweep`` and ``time_lag_s`` itself. + +**Hygiene.** Autoware's range test is written as a rejection (``x < min || x >= max || ...``), so a NaN coordinate +passes it (S:centerpoint:179); the ports drop non-finite rows explicitly (a documented deviation; ``ttaw.io.PointCloud`` +already does it at decode time). Organized clouds mark missing returns as (0, 0, 0): :func:`nonzero_rows` drops them, +as the research references did (``centerpoint_ref.py``), before any transform. + +**Seeded permutation** (S:centerpoint:381-389; PLAN.md D1): Autoware reads its points through a fixed +``std::shuffle`` permutation at a time-seeded random offset, so which <= 32 points an over-full pillar keeps is random. +The ports keep the statistics but are deterministic: ``numpy.random.default_rng(seed).permutation(n)`` before the +first-K-points rule (:func:`seeded_permutation`). + +numpy only; no side effects on import. +""" +from __future__ import annotations + +import collections +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Sequence, Tuple + +import numpy as np + +from .geometry import compose_f32, invert_affine_f32, invert_rigid, transform_points_f32 + +__all__ = [ + "DEFAULT_CLOUD_CAPACITY", + "SweepDensifier", + "StreamDensifiers", + "DensifyInfo", + "densify_sweeps", + "finite_rows", + "nonzero_rows", + "range_mask", + "seeded_permutation", +] + +DEFAULT_CLOUD_CAPACITY = 2_000_000 # centerpoint_common.param.yaml:3 (cloud_capacity) + + +@dataclass +class DensifyInfo: + """What one densification produced: per used sweep its point count and time lag, plus the dropped sweeps.""" + + num_points: int = 0 + sweeps: List[Dict[str, Any]] = field(default_factory=list) # [{"points", "time_lag_s", "age_index"}] + dropped_sweeps: int = 0 # cached sweeps dropped by the capacity rule + + def to_dict(self) -> Dict[str, Any]: + return {"num_points": self.num_points, "sweeps": list(self.sweeps), "dropped_sweeps": self.dropped_sweeps} + + +def _sweep_rows(xyz: np.ndarray, time_lag: np.float32, extra: Optional[np.ndarray], point_feature_size: int, + affine: Optional[np.ndarray]) -> np.ndarray: + """Rows of one sweep in the network layout: (x, y, z, time_lag) or (x, y, z, intensity, time_lag).""" + out = np.empty((len(xyz), point_feature_size), np.float32) + out[:, :3] = xyz if affine is None else transform_points_f32(xyz, affine) + if point_feature_size == 4: + out[:, 3] = time_lag + elif point_feature_size == 5: + out[:, 3] = 0.0 if extra is None else extra + out[:, 4] = time_lag + else: + raise ValueError(f"point_feature_size must be 4 or 5, got {point_feature_size}") + return out + + +@dataclass +class _Cached: + xyz: np.ndarray # (N, 3) float32 in the frame of its own stamp + extra: Optional[np.ndarray] # (N,) float32 intensity (point_feature_size 5) or None + stamp_s: float + past2world: np.ndarray # (4, 4) float32 = Affine3f inverse of world2current at its stamp + + +class SweepDensifier: + """One stream's Autoware densification cache (module docstring). ``num_past_frames`` is + ``densification_params.num_past_frames`` (1 in Autoware's CenterPoint / TransFusion configs).""" + + def __init__(self, num_past_frames: int = 1, cloud_capacity: int = DEFAULT_CLOUD_CAPACITY): + if num_past_frames < 0: + raise ValueError("num_past_frames must be >= 0") + self.num_past_frames = int(num_past_frames) + self.cloud_capacity = int(cloud_capacity) + self._cache: List[_Cached] = [] + self._world2current = np.eye(4, dtype=np.float32) + self._stamp: Optional[float] = None + + @property + def cache_size(self) -> int: + """``pointcloud_cache_size()`` = past frames + the current one.""" + return self.num_past_frames + 1 + + @property + def needs_pose(self) -> bool: + """True when enqueue needs ``T_world_from_sensor`` (Autoware looks up a TF only for cache size > 1).""" + return self.cache_size > 1 + + def __len__(self) -> int: + return len(self._cache) + + @property + def stamps(self) -> List[float]: + """Stamps of the cached sweeps, newest first.""" + return [c.stamp_s for c in self._cache] + + def reset(self) -> None: + self._cache.clear() + self._world2current = np.eye(4, dtype=np.float32) + self._stamp = None + + def enqueue(self, xyz: np.ndarray, stamp_s: float, T_world_from_sensor: Optional[np.ndarray] = None, *, + intensity: Optional[np.ndarray] = None) -> bool: + """``PointCloudDensification::enqueuePointCloud``: returns False, leaving the cache unchanged, when a pose is + needed and missing (Autoware's TF failure: the frame is skipped). ``xyz`` (N, >=3) is in the sensor frame + of ``stamp_s`` (base_link for Autoware's concatenated cloud); ``T_world_from_sensor`` is that frame's pose + in the world (``map``) frame, float64.""" + pts = np.ascontiguousarray(np.asarray(xyz, dtype=np.float32)[:, :3]) + extra = None if intensity is None else np.asarray(intensity, dtype=np.float32).reshape(-1) + if extra is not None and len(extra) != len(pts): + raise ValueError("intensity length differs from the point count") + if self.needs_pose: + if T_world_from_sensor is None: + return False + # tf2 lookupTransform(frame <- world) in double, then .cast() (pointcloud_densification.cpp:47-51) + world2current = invert_rigid(np.asarray(T_world_from_sensor, dtype=np.float64)).astype(np.float32) + else: + world2current = np.eye(4, dtype=np.float32) + self._world2current = world2current + self._stamp = float(stamp_s) + self._cache.insert(0, _Cached(pts, extra, float(stamp_s), invert_affine_f32(world2current))) + if len(self._cache) > self.cache_size: + self._cache.pop() + return True + + def sweep_points(self, *, point_feature_size: int = 4) -> Tuple[np.ndarray, DensifyInfo]: + """``VoxelGenerator::generateSweepPoints``: every cached sweep in the current frame, newest first, as + (N, point_feature_size) float32 rows (x, y, z[, intensity], time_lag).""" + info = DensifyInfo() + if not self._cache: + return np.zeros((0, point_feature_size), np.float32), info + parts: List[np.ndarray] = [] + n = 0 + for k, c in enumerate(self._cache): + if n + len(c.xyz) > self.cloud_capacity: + info.dropped_sweeps = len(self._cache) - k + break + affine = compose_f32(self._world2current, c.past2world) + time_lag = np.float32(self._stamp - c.stamp_s) # double difference cast to float + parts.append(_sweep_rows(c.xyz, time_lag, c.extra, point_feature_size, affine)) + info.sweeps.append({"points": int(len(c.xyz)), "time_lag_s": float(time_lag), "age_index": k}) + n += len(c.xyz) + info.num_points = n + out = np.concatenate(parts, axis=0) if parts else np.zeros((0, point_feature_size), np.float32) + return out, info + + def describe(self) -> Dict[str, Any]: + return {"num_past_frames": self.num_past_frames, "cloud_capacity": self.cloud_capacity, + "cached": len(self._cache), "stamps": self.stamps} + + +class StreamDensifiers: + """Per-stream densification caches (PLAN.md D16: host sweep caches are a per-``stream.id`` dict). A new id beyond + ``max_streams`` evicts the least recently used stream; ``get(id, reset=True)`` restarts one (cold start).""" + + def __init__(self, num_past_frames: int = 1, cloud_capacity: int = DEFAULT_CLOUD_CAPACITY, + max_streams: int = 16): + if max_streams < 1: + raise ValueError("max_streams must be >= 1") + self.num_past_frames = int(num_past_frames) + self.cloud_capacity = int(cloud_capacity) + self.max_streams = int(max_streams) + self._streams: "collections.OrderedDict[str, SweepDensifier]" = collections.OrderedDict() + + def get(self, stream_id: str = "default", *, reset: bool = False) -> SweepDensifier: + sid = str(stream_id) + d = self._streams.get(sid) + if d is None: + d = SweepDensifier(self.num_past_frames, self.cloud_capacity) + self._streams[sid] = d + while len(self._streams) > self.max_streams: + self._streams.popitem(last=False) + elif reset: + d.reset() + self._streams.move_to_end(sid) + return d + + def forget(self, stream_id: str) -> None: + self._streams.pop(str(stream_id), None) + + @property + def streams(self) -> List[str]: + """Stream ids, most recently used first.""" + return list(reversed(self._streams)) + + def describe(self) -> Dict[str, Any]: + return {"max_streams": self.max_streams, "num_past_frames": self.num_past_frames, + "streams": {k: v.describe() for k, v in reversed(self._streams.items())}} + + +def densify_sweeps(current_xyz: np.ndarray, sweeps: Sequence[Tuple[np.ndarray, float, Optional[np.ndarray]]] = (), + *, point_feature_size: int = 4, cloud_capacity: int = DEFAULT_CLOUD_CAPACITY, + current_intensity: Optional[np.ndarray] = None, + sweep_intensity: Optional[Sequence[Optional[np.ndarray]]] = None) -> Tuple[np.ndarray, DensifyInfo]: + """Stateless densification for clients that hold the past sweeps: the current sweep (identity, ``time_lag`` + 0) then each ``(xyz, time_lag_s, T_current_from_sweep)`` in the given order (newest first, as Autoware's cache), + transformed by the float32 sweep kernel (``T`` None = already in the current frame) with + ``time_lag = float32(time_lag_s)``; the capacity rule drops a sweep and every later one.""" + info = DensifyInfo() + cur = np.asarray(current_xyz, dtype=np.float32)[:, :3] + rows = [(cur, np.float32(0.0), current_intensity, None)] + for i, (xyz, lag, T) in enumerate(sweeps): + extra = None if sweep_intensity is None else sweep_intensity[i] + rows.append((np.asarray(xyz, dtype=np.float32)[:, :3], np.float32(lag), extra, + None if T is None else np.asarray(T, dtype=np.float64))) + parts = [] + n = 0 + for k, (xyz, lag, extra, T) in enumerate(rows): + if n + len(xyz) > cloud_capacity: + info.dropped_sweeps = len(rows) - k + break + parts.append(_sweep_rows(xyz, lag, extra, point_feature_size, None if T is None else T.astype(np.float32))) + info.sweeps.append({"points": int(len(xyz)), "time_lag_s": float(lag), "age_index": k}) + n += len(xyz) + info.num_points = n + out = np.concatenate(parts, axis=0) if parts else np.zeros((0, point_feature_size), np.float32) + return out, info + + +# -------------------------------------------------------------------------------------------------- hygiene + +def finite_rows(points: np.ndarray, columns: Sequence[int] = (0, 1, 2)) -> np.ndarray: + """Mask of rows whose ``columns`` are all finite.""" + p = np.asarray(points) + return np.isfinite(p[:, list(columns)]).all(axis=1) + + +def nonzero_rows(points: np.ndarray) -> np.ndarray: + """Mask of rows whose x, y, z are not all exactly zero (organized clouds mark missing returns as (0, 0, 0); the + research references drop them with ``|x| + |y| + |z| > 0``, which also drops non-finite rows).""" + p = np.asarray(points, dtype=np.float32) + return np.abs(p[:, :3]).sum(axis=1) > 0 + + +def range_mask(points: np.ndarray, range_min: Sequence[float], range_max: Sequence[float]) -> np.ndarray: + """Autoware's half-open box test ``min <= v < max`` per axis on x, y, z (float32 comparisons). Unlike Autoware's + rejection form, a NaN coordinate fails it.""" + p = np.asarray(points, dtype=np.float32) + lo = np.asarray(range_min, dtype=np.float32) + hi = np.asarray(range_max, dtype=np.float32) + keep = np.ones(len(p), dtype=bool) + for a in range(3): + keep &= (p[:, a] >= lo[a]) & (p[:, a] < hi[a]) + return keep + + +def seeded_permutation(n: int, seed: Optional[int]) -> Optional[np.ndarray]: + """The deterministic stand-in for Autoware's random point shuffle: ``default_rng(seed).permutation(n)`` (PCG64, + numpy >= 1.17), or None when ``seed`` is None (input order).""" + if seed is None: + return None + return np.random.default_rng(int(seed)).permutation(int(n)) diff --git a/code/tt_depthpro2/ttaw/precision.py b/code/tt_depthpro2/ttaw/precision.py new file mode 100644 index 0000000000000000000000000000000000000000..ec51f4900813c43baf473b99287b37f18f8e6b0f --- /dev/null +++ b/code/tt_depthpro2/ttaw/precision.py @@ -0,0 +1,191 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C05: explicit compute-kernel configs and per-module precision policies. + +Silent defaults this module exists to avoid (TT_PLATFORM.md section 0 item 7, PLAN.md section 0.2): + +- ``ttnn.matmul`` / ``ttnn.linear`` fall back to **LoFi** when a ``program_config`` or ``core_grid`` is given without + a ``compute_kernel_config``; +- ``ttnn.WormholeComputeKernelConfig()`` built without ``math_fidelity`` carries ``MathFidelity.Invalid``. + +So every op that takes a compute config gets one built here, with the fidelity spelled out. The default precision +is HiFi2 + fp32 accumulation, no approximations (the reference bundles' safe start; LoFi failed their gates almost +everywhere, RP section 2.9). A :class:`PrecisionPolicy` maps module names (globs, first match wins) to a +:class:`Precision`; ``_PRECISION`` overrides rules at build time (the A/B switch), e.g. +``CENTERPOINT_PRECISION="backbone.*=HiFi4+fp32;head.*=LoFi:w=bfp8"``. + +Other silent defaults to override by hand (not compute configs): ``ttnn.layer_norm`` epsilon 1e-12, SDPA +``is_causal=True``, ``ttnn.embedding`` PADDED returning the cached pad row, fused HARDSWISH skipped in conv2d. +""" +from __future__ import annotations + +import fnmatch +import os +from dataclasses import asdict, dataclass, replace +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union + +from .tensors import dtype_name + +__all__ = ["FIDELITIES", "Precision", "PRESETS", "compute_kernel_config", "PrecisionPolicy"] + +FIDELITIES = ("LoFi", "HiFi2", "HiFi3", "HiFi4") +_FIDELITY_KEY = {f.lower(): f for f in FIDELITIES} + + +def _fidelity(name: str) -> str: + key = _FIDELITY_KEY.get(str(name).strip().lower()) + if key is None: + raise ValueError(f"math fidelity {name!r}: expected one of {FIDELITIES}") + return key + + +def compute_kernel_config(fidelity: str = "HiFi2", *, fp32_acc: bool = True, approx: bool = False, + packer_l1_acc: bool = False, dst_full_sync: bool = False): + """A ``ttnn.WormholeComputeKernelConfig`` (the same class as ``BlackholeComputeKernelConfig``) with every + field explicit. ``fp32_acc`` = ``fp32_dest_acc_en`` (halves DST capacity: 4 tiles in half-sync).""" + import ttnn + + return ttnn.WormholeComputeKernelConfig(math_fidelity=getattr(ttnn.MathFidelity, _fidelity(fidelity)), + math_approx_mode=bool(approx), fp32_dest_acc_en=bool(fp32_acc), + packer_l1_acc=bool(packer_l1_acc), dst_full_sync_en=bool(dst_full_sync)) + + +@dataclass(frozen=True) +class Precision: + """Fidelity / accumulation / dtype choice of one module (an op or a group of ops).""" + + fidelity: str = "HiFi2" + fp32_acc: bool = True + approx: bool = False + packer_l1_acc: bool = False + dst_full_sync: bool = False + weights: str = "bfloat16" + activations: str = "bfloat16" + + def __post_init__(self) -> None: + object.__setattr__(self, "fidelity", _fidelity(self.fidelity)) + object.__setattr__(self, "weights", dtype_name(self.weights)) + object.__setattr__(self, "activations", dtype_name(self.activations)) + + @classmethod + def parse(cls, spec: Union[str, "Precision"]) -> "Precision": + """``"HiFi4+fp32"``, ``"LoFi"``, ``"HiFi2+fp32+approx+l1acc:w=bfp8:a=bf16"`` or a preset name + (``accurate`` / ``balanced`` / ``fast``). Flags: ``fp32`` (fp32 accumulation; absent = bf16 DST), + ``approx``, ``l1acc``, ``fullsync``; ``w=`` / ``a=`` set weight / activation dtypes.""" + if isinstance(spec, Precision): + return spec + text = spec.strip() + if text.lower() in PRESETS: + return PRESETS[text.lower()] + head, *opts = text.split(":") + fid, *flags = [p.strip() for p in head.split("+")] + kw: Dict[str, Any] = {"fidelity": fid, "fp32_acc": False} + for flag in (f.lower() for f in flags): + if flag == "fp32": + kw["fp32_acc"] = True + elif flag == "approx": + kw["approx"] = True + elif flag == "l1acc": + kw["packer_l1_acc"] = True + elif flag == "fullsync": + kw["dst_full_sync"] = True + else: + raise ValueError(f"precision {spec!r}: unknown flag {flag!r}") + for opt in opts: + k, _, v = opt.partition("=") + k = k.strip().lower() + if k in ("w", "weights"): + kw["weights"] = v.strip() + elif k in ("a", "act", "activations"): + kw["activations"] = v.strip() + else: + raise ValueError(f"precision {spec!r}: unknown option {k!r}") + return cls(**kw) + + @property + def label(self) -> str: + """Round-trips through :meth:`parse`.""" + flags = "".join(f"+{f}" for f, on in (("fp32", self.fp32_acc), ("approx", self.approx), + ("l1acc", self.packer_l1_acc), ("fullsync", self.dst_full_sync)) if on) + return f"{self.fidelity}{flags}:w={self.weights}:a={self.activations}" + + def with_(self, **changes: Any) -> "Precision": + return replace(self, **changes) + + def compute_kernel_config(self): + return compute_kernel_config(self.fidelity, fp32_acc=self.fp32_acc, approx=self.approx, + packer_l1_acc=self.packer_l1_acc, dst_full_sync=self.dst_full_sync) + + def weights_dtype(self): + from .tensors import ttnn_dtype + + return ttnn_dtype(self.weights) + + def activations_dtype(self): + from .tensors import ttnn_dtype + + return ttnn_dtype(self.activations) + + def to_dict(self) -> Dict[str, Any]: + return asdict(self) + + +PRESETS: Dict[str, Precision] = { + "accurate": Precision("HiFi4", fp32_acc=True), # norms, softmax logits, box regression, grid sampling + "balanced": Precision("HiFi2", fp32_acc=True), # default for big matmuls / convs + "fast": Precision("LoFi", fp32_acc=False, weights="bfloat8_b"), # only after the gates pass with it +} + +RuleSpec = Union[Mapping[str, Union[str, Precision]], Sequence[Tuple[str, Union[str, Precision]]]] + + +class PrecisionPolicy: + """Ordered ``pattern -> Precision`` rules (``fnmatch`` globs on dotted module names, first match wins) plus a + default. Typical use, once at model build:: + + POLICY = PrecisionPolicy({"backbone.*": "balanced", "head.reg*": "accurate"}, default="balanced") + policy = POLICY.with_env("CENTERPOINT") # _PRECISION overrides, read once + cfg = policy.compute_kernel_config("backbone.block3.conv2") + w_dtype = policy.resolve("backbone.block3.conv2").weights_dtype() + + ``resolve`` records each module it answered for, so ``describe()`` shows the policy that reached the ops.""" + + def __init__(self, rules: Optional[RuleSpec] = None, default: Union[str, Precision] = "balanced"): + items = rules.items() if isinstance(rules, Mapping) else (rules or ()) + self.rules: List[Tuple[str, Precision]] = [(str(p), Precision.parse(v)) for p, v in items] + self.default = Precision.parse(default) + self.used: Dict[str, str] = {} + self._configs: Dict[Precision, Any] = {} + + def resolve(self, module: str) -> Precision: + for pattern, prec in self.rules: + if fnmatch.fnmatchcase(module, pattern): + self.used[module] = prec.label + return prec + self.used[module] = self.default.label + return self.default + + def compute_kernel_config(self, module: str): + prec = self.resolve(module) + if prec not in self._configs: + self._configs[prec] = prec.compute_kernel_config() + return self._configs[prec] + + def override(self, spec: str) -> "PrecisionPolicy": + """A new policy with ``"pattern=precision;pattern=precision"`` rules placed before the existing ones + (``*=...`` effectively replaces the default for unmatched modules).""" + extra = [] + for part in filter(None, (p.strip() for p in spec.split(";"))): + pattern, sep, prec = part.partition("=") + if not sep: + raise ValueError(f"precision override {part!r}: expected pattern=precision") + extra.append((pattern.strip(), Precision.parse(prec))) + return PrecisionPolicy(extra + self.rules, self.default) + + def with_env(self, prefix: str, env: Optional[Mapping[str, str]] = None) -> "PrecisionPolicy": + """Apply ``_PRECISION`` if set (else return ``self``). Call once at build.""" + spec = (os.environ if env is None else env).get(f"{prefix}_PRECISION", "").strip() + return self.override(spec) if spec else self + + def describe(self) -> Dict[str, Any]: + return {"default": self.default.label, "rules": [[p, prec.label] for p, prec in self.rules], + "used": dict(sorted(self.used.items()))} diff --git a/code/tt_depthpro2/ttaw/profiling.py b/code/tt_depthpro2/ttaw/profiling.py new file mode 100644 index 0000000000000000000000000000000000000000..66b2a2fef780aeccf1a151e36ae1ed4789e81c68 --- /dev/null +++ b/code/tt_depthpro2/ttaw/profiling.py @@ -0,0 +1,440 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C07: measurement helpers -- the numbers OPT_BASELINE.md / OPT_REPORT.md / the model card quote. + +- :class:`StageBench` collects wall times per stage (``host_in``, ``h2d``, ``trace``, ``b2b``, ``d2h``, ``post``, + ``e2e``) and reports p50 / p99 / mean / min / max in ms (RP section 3, rf-detr ``bench_breakdown``). +- :func:`bench_trace_runner` measures those stages on a :class:`.trace.TraceRunner` variant. +- :func:`signpost` / :func:`signposted` mark Tracy ranges (no-ops when the ``tracy`` module is absent), so + ``tt-perf-report --start-signpost trace --end-signpost trace_end`` and :func:`summarize_ops` can cut the CSV. +- :func:`summarize_ops` reads a device-profiler ``ops_perf_results*.csv`` (Tracy ``-r``) or the C++ + ``cpp_device_perf_report.csv`` and returns op count, kernel sum, op-to-op gaps, span, per-op-code totals and the + math-fidelity histogram. CLI: ``python -m .ttaw.profiling [--start trace] [--json out.json]``. +- :class:`AiclkSampler` samples the chip clock (sysfs ``tt_aiclk``) and hwmon power / temperature in a background + thread during a bench: AICLK sags from 1350 MHz under load (RP section 3), which explains span-vs-wall gaps. + +Profiling runs go through ``bin/devrun`` like any device job, with an absolute output directory under +``generated/profiler/_`` (PLAN.md section 5.1). +""" +from __future__ import annotations + +import argparse +import contextlib +import csv +import glob +import json +import logging +import os +import statistics +import sys +import threading +import time +from collections import defaultdict +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Dict, Iterator, List, Mapping, Optional, Sequence, Union + +import numpy as np + +__all__ = [ + "STAGES", + "StageBench", + "time_b2b", + "bench_trace_runner", + "signpost", + "signposted", + "read_device_profiler", + "find_ops_csv", + "OpsSummary", + "summarize_ops", + "AiclkSampler", +] + +log = logging.getLogger(__name__) +STAGES = ("host_in", "h2d", "trace", "b2b", "d2h", "post", "e2e") +DEFAULT_AICLK_MHZ = 1350.0 + + +# ------------------------------------------------------------------------------------------- stage bench + +def _stats(samples: Sequence[float]) -> Dict[str, float]: + a = np.asarray(samples, np.float64) + return {"n": int(a.size), "p50": float(np.percentile(a, 50)), "p99": float(np.percentile(a, 99)), + "mean": float(a.mean()), "min": float(a.min()), "max": float(a.max())} + + +class StageBench: + """Per-stage wall-time samples in milliseconds. + + :: + + bench = StageBench("centerpoint eth/1cq") + for _ in range(100): + with bench.stage("e2e"): + with bench.stage("host_in"): host = prepare(points) + ... + print(bench.table()); bench.save_json("logs/centerpoint/bench_baseline.json", config=device_info) + """ + + def __init__(self, name: str = ""): + self.name = name + self.samples: Dict[str, List[float]] = {} + + @contextlib.contextmanager + def stage(self, name: str) -> Iterator[None]: + t0 = time.perf_counter() + try: + yield + finally: + self.add(name, (time.perf_counter() - t0) * 1e3) + + def add(self, name: str, ms: float) -> None: + self.samples.setdefault(name, []).append(float(ms)) + + def summary(self) -> Dict[str, Dict[str, float]]: + """``{stage: {n, p50, p99, mean, min, max}}`` in ms; known stages first, in pipeline order.""" + order = [s for s in STAGES if s in self.samples] + [s for s in self.samples if s not in STAGES] + return {s: _stats(self.samples[s]) for s in order if self.samples[s]} + + def table(self) -> str: + rows = [f"| stage | n | p50 ms | p99 ms | mean ms | min ms |", "|---|---:|---:|---:|---:|---:|"] + for s, st in self.summary().items(): + rows.append(f"| {s} | {st['n']} | {st['p50']:.3f} | {st['p99']:.3f} | {st['mean']:.3f} | {st['min']:.3f} |") + return (f"**{self.name}**\n\n" if self.name else "") + "\n".join(rows) + + def to_dict(self, **extra: Any) -> Dict[str, Any]: + return {"name": self.name, "stages_ms": self.summary(), **extra} + + def save_json(self, path: Union[str, os.PathLike], **extra: Any) -> Path: + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(self.to_dict(**extra), indent=1, default=str) + "\n") + return path + + +def time_b2b(enqueue: Callable[[], Any], sync: Callable[[], Any], n: int = 100, warmup: int = 5) -> float: + """Back-to-back device time per iteration (ms): ``warmup`` + ``n`` non-blocking ``enqueue()`` calls, one + ``sync()`` each round. With a traced ``enqueue`` this is the device time per forward.""" + for _ in range(warmup): + enqueue() + sync() + t0 = time.perf_counter() + for _ in range(n): + enqueue() + sync() + return (time.perf_counter() - t0) * 1e3 / n + + +def bench_trace_runner(runner, variant: Optional[str], inputs: Mapping[str, Any], *, + params: Optional[Mapping[str, Any]] = None, iters: int = 100, warmup: int = 10, + post: Optional[Callable[[Any], Any]] = None, b2b_iters: Optional[int] = None, + name: str = "") -> StageBench: + """Stage breakdown of one :class:`.trace.TraceRunner` variant (medians are the headline numbers): + + ``host_in`` host tensor conversion, ``h2d`` upload + sync, ``trace`` one replay + sync, ``d2h`` read, + ``post`` the optional ``post(outputs)`` callback, ``e2e`` ``runner(variant, inputs)`` + ``post``, and ``b2b`` + back-to-back replays (device time per forward).""" + import ttnn + + from .tensors import to_host_tensor + + dev = runner.device + bench = StageBench(name or f"{runner.name}/{variant}") + slots = {k: runner._slot(k, "input") for k in inputs} + for _ in range(warmup): + out = runner(variant, inputs, params) + if post is not None: + post(out) + for _ in range(iters): + t0 = time.perf_counter() + host = {k: to_host_tensor(v, slots[k].dtype, slots[k].layout, shape=slots[k].shape) for k, v in inputs.items()} + t1 = time.perf_counter() + runner.upload(host, params) + ttnn.synchronize_device(dev) + t2 = time.perf_counter() + runner.replay(variant) + ttnn.synchronize_device(dev) + t3 = time.perf_counter() + out = runner.read(variant) + t4 = time.perf_counter() + if post is not None: + post(out) + t5 = time.perf_counter() + for stage, a, b in (("host_in", t0, t1), ("h2d", t1, t2), ("trace", t2, t3), ("d2h", t3, t4)): + bench.add(stage, (b - a) * 1e3) + if post is not None: + bench.add("post", (t5 - t4) * 1e3) + for _ in range(iters): + with bench.stage("e2e"): + out = runner(variant, inputs, params) + if post is not None: + post(out) + bench.add("b2b", time_b2b(lambda: runner.replay(variant), lambda: ttnn.synchronize_device(dev), + n=b2b_iters or iters)) + return bench + + +# --------------------------------------------------------------------------------------------- signposts + +def signpost(name: str, message: Optional[str] = None) -> bool: + """Emit a Tracy signpost (a row in the ops CSV); returns False (no-op) when ``tracy`` is not importable.""" + try: + from tracy import signpost as _signpost + except ImportError: + return False + _signpost(header=name, message=message) + return True + + +@contextlib.contextmanager +def signposted(name: str) -> Iterator[None]: + """``signpost(name)`` ... ``signpost(name + "_end")`` around the block.""" + signpost(name) + try: + yield + finally: + signpost(f"{name}_end") + + +def read_device_profiler(device) -> bool: + """Flush the device profiler buffer (``ttnn.ReadDeviceProfiler``); call it per trace segment, the buffer holds + about 1000 ops. Returns False when the API is absent.""" + import ttnn + + fn = getattr(ttnn, "ReadDeviceProfiler", None) + if fn is None: + return False + fn(device) + return True + + +# ------------------------------------------------------------------------------------- ops CSV summary + +def find_ops_csv(path: Union[str, os.PathLike]) -> Path: + """A CSV file as-is, or the newest ``ops_perf_results*.csv`` (else ``cpp_device_perf_report.csv``) below a dir.""" + p = Path(path) + if p.is_file(): + return p + for pattern in ("ops_perf_results*.csv", "cpp_device_perf_report.csv"): + found = sorted(glob.glob(str(p / "**" / pattern), recursive=True), key=os.path.getmtime) + if found: + return Path(found[-1]) + raise FileNotFoundError(f"no ops_perf_results*.csv or cpp_device_perf_report.csv under {p}") + + +def _num(row: Mapping[str, str], key: str) -> float: + value = (row.get(key) or "").strip() + try: + return float(value) if value else 0.0 + except ValueError: + return 0.0 + + +def _chip_freq_mhz(csv_path: Path) -> Optional[float]: + """CHIP_FREQ[MHz] from a ``profile_log_device.csv`` header near the ops CSV, if any.""" + for cand in [csv_path.parent / "profile_log_device.csv", csv_path.parent.parent / "profile_log_device.csv", + csv_path.parent / ".logs" / "profile_log_device.csv"]: + try: + head = cand.read_text(errors="ignore").splitlines()[0] + except (OSError, IndexError): + continue + for part in head.split(","): + if "CHIP_FREQ" in part and ":" in part: + try: + return float(part.split(":")[1].strip()) + except ValueError: + pass + return None + + +@dataclass +class OpsSummary: + """Summary of one profiled section (times in microseconds).""" + + source: str + section: str + ops: int + kernel_sum_us: float + fw_sum_us: float + op2op_sum_us: float + span_us: Optional[float] + freq_mhz: float + by_op: List[Dict[str, Any]] = field(default_factory=list) + fidelity: Dict[str, int] = field(default_factory=dict) + top_gaps: List[Dict[str, Any]] = field(default_factory=list) + + def to_dict(self) -> Dict[str, Any]: + return {k: getattr(self, k) for k in self.__dataclass_fields__} + + def table(self, top: int = 20) -> str: + span = "n/a" if self.span_us is None else f"{self.span_us:.1f}" + lines = [f"{self.source} [{self.section}]", + f"ops {self.ops} kernel_sum {self.kernel_sum_us:.1f} us op2op_sum {self.op2op_sum_us:.1f} us " + f"span {span} us (@{self.freq_mhz:.0f} MHz) fidelity {self.fidelity}", + f"{'op code':55s} {'count':>6s} {'kernel us':>11s} {'share':>7s}"] + for row in self.by_op[:top]: + lines.append(f"{row['op'][:55]:55s} {row['count']:6d} {row['kernel_us']:11.1f} {row['share']:6.1%}") + return "\n".join(lines) + + +def summarize_ops(source: Union[str, os.PathLike, Sequence[Mapping[str, str]]], *, start: Optional[str] = "trace", + end: Optional[str] = None, last_replay_session: Optional[bool] = None, + freq_mhz: Optional[float] = None, top_gaps: int = 10) -> OpsSummary: + """Summarize device ops between signposts ``start`` and ``end`` (default: the next signpost). + + ``source``: an ``ops_perf_results*.csv`` / ``cpp_device_perf_report.csv`` path, a directory holding one, or + already-parsed rows. ``start=None`` takes every op. ``last_replay_session`` (default: on when the rows carry + ``METAL TRACE REPLAY SESSION ID`` values) keeps only the last trace replay session, the way ``prof_cpp.py`` + did. Span uses the FW start/end cycles at ``freq_mhz`` (default: the CHIP_FREQ of ``profile_log_device.csv``, + else 1350 MHz; AICLK sags under load, so treat span as approximate).""" + if isinstance(source, (str, os.PathLike)): + path = find_ops_csv(source) + with open(path, newline="") as f: + rows = list(csv.DictReader(f)) + label = str(path) + freq = freq_mhz or _chip_freq_mhz(path) or DEFAULT_AICLK_MHZ + else: + rows, label, freq = list(source), "", freq_mhz or DEFAULT_AICLK_MHZ + name_key = "OP CODE" if rows and "OP CODE" in rows[0] else "OP NAME" + section = "all" + if start is not None and any((r.get("OP TYPE") or "") == "signpost" for r in rows): + selected, on = [], False + for r in rows: + if (r.get("OP TYPE") or "") == "signpost": + code = r.get(name_key, "") + if on and (end is None or code == end): + break + on = on or code == start + continue + if on: + selected.append(r) + rows, section = selected, f"{start}..{end or 'next signpost'}" + else: + rows = [r for r in rows if (r.get("OP TYPE") or "") != "signpost"] + sessions = [r.get("METAL TRACE REPLAY SESSION ID", "") for r in rows] + if last_replay_session is None: + last_replay_session = any(s.strip() for s in sessions) + if last_replay_session and rows: + traced = [r for r in rows if (r.get("METAL TRACE ID") or "").strip()] + if traced: + last = traced[-1].get("METAL TRACE REPLAY SESSION ID") + rows = [r for r in traced if r.get("METAL TRACE REPLAY SESSION ID") == last] + section += f" (replay session {last})" + kernel = [_num(r, "DEVICE KERNEL DURATION [ns]") / 1e3 for r in rows] + fw = [_num(r, "DEVICE FW DURATION [ns]") / 1e3 for r in rows] + gaps = [_num(r, "OP TO OP LATENCY [ns]") / 1e3 for r in rows] + starts = [_num(r, "DEVICE FW START CYCLE") for r in rows] + ends = [_num(r, "DEVICE FW END CYCLE") for r in rows] + span = (max(ends) - min(s for s in starts if s > 0)) / freq if rows and any(starts) and any(ends) else None + agg: Dict[str, List[float]] = defaultdict(lambda: [0, 0.0]) + fidelity: Dict[str, int] = defaultdict(int) + for r, k in zip(rows, kernel): + agg[r.get(name_key, "?")][0] += 1 + agg[r.get(name_key, "?")][1] += k + fid = (r.get("MATH FIDELITY") or "").strip() + if fid: + fidelity[fid] += 1 + total = sum(kernel) or 1.0 + by_op = [{"op": op, "count": int(c), "kernel_us": t, "share": t / total} + for op, (c, t) in sorted(agg.items(), key=lambda kv: -kv[1][1])] + order = sorted(range(1, len(rows)), key=lambda i: -gaps[i])[:top_gaps] + worst = [{"index": i, "op": rows[i].get(name_key, "?"), "gap_us": gaps[i], "after": rows[i - 1].get(name_key, "?")} + for i in order] + return OpsSummary(label, section, len(rows), sum(kernel), sum(fw), sum(gaps[1:]), span, freq, by_op, + dict(fidelity), worst) + + +# ------------------------------------------------------------------------------------------------ AICLK + +class AiclkSampler: + """Background sampling of ``tt_aiclk`` (MHz) and hwmon power (W) / temperature (C) of one chip. + + :: + + with AiclkSampler(chip=0, interval_s=0.05) as clk: + run_bench() + print(clk.summary()) # {"aiclk_mhz": {"median": 1302, "min": 1206, ...}, "power_w": {...}, ...} + + Reads sysfs only (read-only, works while another process holds the device); ``available`` is False on hosts + without the Tenstorrent KMD.""" + + def __init__(self, chip: int = 0, interval_s: float = 0.05, *, root: str = "/sys/class/tenstorrent"): + self.interval_s = float(interval_s) + base = Path(root) / f"tenstorrent!{chip}" + self._aiclk = base / "tt_aiclk" + hwmon = sorted(glob.glob(str(base / "device" / "hwmon" / "hwmon*"))) + self._hwmon = Path(hwmon[0]) if hwmon else None + self.available = self._aiclk.is_file() + self.samples: Dict[str, List[float]] = {"aiclk_mhz": [], "power_w": [], "temp_c": []} + self._stop = threading.Event() + self._thread: Optional[threading.Thread] = None + + @staticmethod + def _read(path: Optional[Path], scale: float) -> Optional[float]: + if path is None: + return None + try: + return float(path.read_text().split()[0]) * scale + except (OSError, ValueError, IndexError): + return None + + def sample_once(self) -> Dict[str, Optional[float]]: + hw = self._hwmon + values = {"aiclk_mhz": self._read(self._aiclk, 1.0), + "power_w": self._read(hw / "power1_input" if hw else None, 1e-6), + "temp_c": self._read(hw / "temp1_input" if hw else None, 1e-3)} + for k, v in values.items(): + if v is not None: + self.samples[k].append(v) + return values + + def _loop(self) -> None: + while not self._stop.is_set(): + self.sample_once() + self._stop.wait(self.interval_s) + + def start(self) -> "AiclkSampler": + if self.available and self._thread is None: + self._stop.clear() + self._thread = threading.Thread(target=self._loop, name="aiclk-sampler", daemon=True) + self._thread.start() + return self + + def stop(self) -> None: + if self._thread is not None: + self._stop.set() + self._thread.join(timeout=5) + self._thread = None + + def __enter__(self) -> "AiclkSampler": + return self.start() + + def __exit__(self, *exc) -> None: + self.stop() + + def summary(self) -> Dict[str, Any]: + out: Dict[str, Any] = {"available": self.available} + for k, v in self.samples.items(): + if v: + out[k] = {"median": statistics.median(v), "min": min(v), "max": max(v), "n": len(v)} + return out + + +def main(argv: Optional[Sequence[str]] = None) -> int: + """``python -m .ttaw.profiling [--start trace] [--end trace_end] [--json out] [--top 25]``.""" + ap = argparse.ArgumentParser(description="Summarize a device-profiler ops CSV") + ap.add_argument("source") + ap.add_argument("--start", default="trace", help="signpost that opens the section ('' = all ops)") + ap.add_argument("--end", default=None) + ap.add_argument("--freq-mhz", type=float, default=None) + ap.add_argument("--top", type=int, default=25) + ap.add_argument("--json", default=None) + a = ap.parse_args(argv) + summary = summarize_ops(a.source, start=a.start or None, end=a.end, freq_mhz=a.freq_mhz) + print(summary.table(a.top)) + if a.json: + Path(a.json).write_text(json.dumps(summary.to_dict(), indent=1) + "\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/code/tt_depthpro2/ttaw/server/__init__.py b/code/tt_depthpro2/ttaw/server/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..387839e47a6170bb57a15d7c4517389dfc34b02f --- /dev/null +++ b/code/tt_depthpro2/ttaw/server/__init__.py @@ -0,0 +1,15 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C08 HTTP serving shared by every bundle. + +- ``server.app``: :func:`create_app` builds the FastAPI (ASGI) app of a bundle from a :class:`ServerSpec` + (routes ``/``, ``/health``, ``/v1/health``, ``/info``, ``/v1/models``, ``/predict``; lifespan = weights -> device -> + graph -> trace capture; errors 400 / 422 / 503 / 500). Imports fastapi / pydantic. +- ``server.client``: standard-library-only request builder, HTTP helpers and smoke checks (``/info`` must report + the pinned dispatch and grid). +- ``server.smoke``: standard-library-only agreement of a served body with a stored CPU-reference body (every output + family, numpy-free npz / png decoding) and the serve-profile pins of a staged tt-model manifest. + +Neither imports anything from ttaw, so a bundle's ``smoke_test.py`` can load them by path and run under any +Python 3.9+ outside the container. This ``__init__`` imports nothing, so ``import .ttaw.server.client`` never +pulls in fastapi. +""" diff --git a/code/tt_depthpro2/ttaw/server/app.py b/code/tt_depthpro2/ttaw/server/app.py new file mode 100644 index 0000000000000000000000000000000000000000..e8dc225a5ec6631cff0cc02651aae8ae23ad2665 --- /dev/null +++ b/code/tt_depthpro2/ttaw/server/app.py @@ -0,0 +1,401 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C08 server: the FastAPI app factory implementing the HTTP contract of all 13 bundles (BUNDLE_CONVENTIONS.md 7). + +A bundle's ``server/app.py`` is a few lines:: + + from ..api import CenterPoint + from ..ttaw.server.app import ServerSpec, create_app, parse_mesh_shape # noqa: F401 (verify: line) + + SPEC = ServerSpec(model_name=CenterPoint.MODEL_NAME, env_prefix="CENTERPOINT", model_cls=CenterPoint, + task="LiDAR 3D object detection", default_weights=CenterPoint.DEFAULT_REPO, + io="a LiDAR point cloud in, 3D boxes out", + autoware={"package": "autoware_lidar_centerpoint", + "path": "perception/autoware_lidar_centerpoint", + "autoware_universe": "9ceaccf026c31ffc5319bc9eeb4bd7bede0af3fd"}, + source={"repo": "https://huggingface.co/changh95/centerpoint-p150", "license": "Apache-2.0"}, + calib_dir=Path(__file__).resolve().parents[1] / "calib") + app = create_app(SPEC) + +Served by tt-model-manager as ``kind: tt-dit-server`` (``python -m uvicorn --lifespan on .server.app:app``). +Everything device-touching happens in the lifespan: weights -> device -> graph -> trace capture of every warm-up +variant; uvicorn logs ``Application startup complete`` only after that, so READY means warm. Shutdown (SIGTERM, +120 s budget) closes the model under the lock. Importing the module has no side effects beyond importing +fastapi / pydantic (no device, no download, no environment read). + +Tests replace the model with a stub: ``app.state.ttaw.model_factory = StubModel`` before ``TestClient(app)``. +``app.state.ttaw.predict(request)`` is the route handler itself (for API == server checks). + +Environment (read in the lifespan): ``HF_MODEL``, ``TT_MODEL_WEIGHTS_REVISION`` (then ``TT_WEIGHTS_REVISION``), +``_WEIGHTS_DIR``, ``TT_MESH_SHAPE`` (only 1x1), ``TT_DEVICE_ID``, ``_DISPATCH``, ``_NUM_CQS``, +``_VARIANT``, ``_WARMUP`` (JSON list, ``default`` or ``none``), ``_MAX_BODY_MB`` (default 256), +``_TORCH_THREADS``. +""" +import json +import logging +import math +import os +import re +import threading +import time +from contextlib import asynccontextmanager +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Dict, List, Literal, Mapping, Optional, Type + +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict, Field + +from .. import io as tio + +__all__ = [ + "HARDWARE", "PointsSpec", "SweepSpec", "ImageSpec", "StreamSpec", "ArraysSpec", "PredictRequest", "ServerSpec", + "ServerState", "parse_mesh_shape", "config_from_env", "default_model_factory", "decode_request", "create_app", +] + +HARDWARE = "Tenstorrent Blackhole p150 (single chip) via tt-nn" +log = logging.getLogger("ttaw.server") + + +# ------------------------------------------------------------------------------------------- request schema + +class _Strict(BaseModel): + model_config = ConfigDict(extra="forbid") # a misspelled field is a 422, not a silently ignored option + + +class PointsSpec(_Strict): + format: Literal["bin", "npy", "npz", "pcd", "list"] = "bin" + data: Optional[str] = None # base64 of the file bytes (all formats except "list") + values: Optional[List[List[float]]] = None # "list" only + fields: Optional[List[str]] = None # column names (required meaning for "bin" / "list") + dtype: Literal["float32", "float64"] = "float32" + key: Optional[str] = None # "npz" only + frame_id: Optional[str] = None + + +class SweepSpec(_Strict): + points: PointsSpec + time_lag_s: float = 0.0 # age of this sweep relative to the current one + T_current_from_sweep: Optional[Any] = None # 4x4 / {translation, rotation_wxyz} / {x, y, z, roll, pitch, yaw} + + +class ImageSpec(_Strict): + camera: str + data: str # base64 PNG / JPEG (or .npy uint8 HxWx3) + format: Literal["auto", "png", "jpeg", "npy"] = "auto" + intrinsics: Optional[Any] = None # 3x3 / 3x4 / {fx, fy, cx, cy} + T_ref_from_camera: Optional[Any] = None + distortion: Optional[Dict[str, Any]] = None + timestamp_s: Optional[float] = None + + +class StreamSpec(_Strict): + id: str = "default" + reset: bool = False + timestamp_s: Optional[float] = None + T_world_from_ego: Optional[Any] = None + + +class ArraysSpec(_Strict): + format: Literal["npz", "json"] = "npz" + data: Optional[str] = None + arrays: Optional[Dict[str, Any]] = None + + +class PredictRequest(_Strict): + """The common ``POST /predict`` envelope. Bundles with extra inputs subclass it (e.g. PointPainting ``rois``) + and decode the extra fields in ``ServerSpec.decode_extra``.""" + + points: Optional[PointsSpec] = None + sweeps: Optional[List[SweepSpec]] = None + images: Optional[List[ImageSpec]] = None + calibration: Optional[Dict[str, Any]] = None + stream: Optional[StreamSpec] = None + inputs: Optional[ArraysSpec] = None + params: Dict[str, Any] = Field(default_factory=dict) + output_format: Literal["json", "npz"] = "json" + + +# ----------------------------------------------------------------------------------------------- config + +@dataclass +class ServerSpec: + """Identity and hooks of one bundle's server. ``model_cls`` is the bundle's ``ModelBase`` subclass (used by the + default factory and for ``CAMERA_ORDER`` / calibration rules).""" + + model_name: str + env_prefix: str + model_cls: Any = None + task: str = "" + default_weights: str = "" + owner: str = "changh95" + hardware: str = HARDWARE + io: str = "" + autoware: Mapping[str, Any] = field(default_factory=dict) + source: Mapping[str, Any] = field(default_factory=dict) + calib_dir: Optional[Path] = None + default_variant: Optional[str] = None + version: str = "0.1.0" + description: str = "" + request_model: Type[PredictRequest] = PredictRequest + # decode_extra(request, kwargs, max_bytes): add model-specific call kwargs from extra request fields + decode_extra: Optional[Callable[[Any, Dict[str, Any], int], None]] = None + # info_extra(model) -> dict merged into /info + info_extra: Optional[Callable[[Any], Dict[str, Any]]] = None + + +_SHAPE_RE = re.compile(r"^\s*[\(\[]?\s*(\d+)\s*[xX,]\s*(\d+)\s*[\)\]]?\s*$") + + +def parse_mesh_shape(value: Optional[str]) -> tuple: + """``"1x1"`` / ``"(1, 1)"`` / ``"1,1"`` -> ``(1, 1)``; unset -> ``(1, 1)``.""" + if value is None or not value.strip(): + return (1, 1) + m = _SHAPE_RE.match(value) + if not m: + raise RuntimeError(f"TT_MESH_SHAPE={value!r} is not a mesh shape; expected '1x1', '(1, 1)' or '1,1'") + return (int(m.group(1)), int(m.group(2))) + + +def config_from_env(spec: ServerSpec, env: Optional[Mapping[str, str]] = None) -> Dict[str, Any]: + """The server configuration from the environment (read once, in the lifespan).""" + env = os.environ if env is None else env + p = spec.env_prefix + warm = (env.get(f"{p}_WARMUP") or "default").strip() or "default" + default_variant = spec.default_variant or getattr(spec.model_cls, "DEFAULT_VARIANT", None) or "default" + return { + "model_id": env.get("HF_MODEL") or spec.default_weights, + "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, + "mesh_shape": parse_mesh_shape(env.get("TT_MESH_SHAPE")), + "device_id": int(env.get("TT_DEVICE_ID") or 0), + "dispatch": (env.get(f"{p}_DISPATCH") or "eth").strip().lower(), + "num_command_queues": int(env.get(f"{p}_NUM_CQS") or 0) or None, + "variant": env.get(f"{p}_VARIANT") or default_variant, + "warmup_variants": warm if warm in ("default", "none") else json.loads(warm), + "max_body_bytes": int(float(env.get(f"{p}_MAX_BODY_MB") or 256) * (1 << 20)), + "torch_threads": env.get(f"{p}_TORCH_THREADS") or None, + } + + +def default_model_factory(spec: ServerSpec) -> Callable[[Dict[str, Any]], Any]: + """``cfg -> spec.model_cls.from_pretrained(...)``.""" + + def factory(cfg: Dict[str, Any]) -> Any: + if spec.model_cls is None: + raise RuntimeError(f"{spec.model_name}: ServerSpec.model_cls is not set and no model_factory was given") + return spec.model_cls.from_pretrained(cfg["model_id"] or None, revision=cfg["revision"], + weights_dir=cfg["weights_dir"], variant=cfg["variant"], + device_id=cfg["device_id"], dispatch=cfg["dispatch"], + num_command_queues=cfg["num_command_queues"], + warmup_variants=cfg["warmup_variants"]) + + return factory + + +@dataclass +class ServerState: + """Per-app state (``app.state.ttaw``).""" + + spec: ServerSpec + model_factory: Callable[[Dict[str, Any]], Any] + ready: bool = False + error: Optional[str] = None + model: Any = None + config: Dict[str, Any] = field(default_factory=dict) + boot_ms: Optional[float] = None + lock: Any = field(default_factory=threading.Lock) # one chip, batch 1: device calls are serialized + predict: Optional[Callable[[Any], Dict[str, Any]]] = None + + def status(self) -> str: + return "ok" if self.ready else ("error" if self.error else "starting") + + def device_desc(self) -> Optional[Dict[str, Any]]: + return getattr(self.model, "device_info", None) if self.model is not None else None + + +def _non_finite_path(obj: Any, path: str = "body") -> Optional[str]: + """Location of the first NaN / infinite float in a JSON-able body (None if there is none).""" + if isinstance(obj, float): + return None if math.isfinite(obj) else path + if isinstance(obj, Mapping): + for k, v in obj.items(): + found = _non_finite_path(v, f"{path}.{k}") + if found is not None: + return found + elif isinstance(obj, (list, tuple)): + for i, v in enumerate(obj): + found = _non_finite_path(v, f"{path}[{i}]") + if found is not None: + return found + return None + + +def decode_request(req: PredictRequest, spec: ServerSpec, max_bytes: int) -> Dict[str, Any]: + """JSON envelope -> the Python-API call kwargs (all client errors raise ``io.InputError``).""" + cls = spec.model_cls + fields = tuple(getattr(cls, "POINT_FIELDS", tio.DEFAULT_POINT_FIELDS)) + kw: Dict[str, Any] = {} + if req.points is not None: + kw["points"] = tio.decode_points(req.points.model_dump(exclude_none=True), max_bytes=max_bytes, + default_fields=fields) + if req.sweeps: + kw["sweeps"] = [{"points": tio.decode_points(s.points.model_dump(exclude_none=True), max_bytes=max_bytes, + default_fields=fields), + "time_lag_s": s.time_lag_s, + "T_current_from_sweep": None if s.T_current_from_sweep is None else + tio.parse_transform(s.T_current_from_sweep, field="sweeps[].T_current_from_sweep")} + for s in req.sweeps] + calib = tio.resolve_calibration(req.calibration, spec.calib_dir) + if req.images: + order = tuple(getattr(cls, "CAMERA_ORDER", ()) or ()) or None + require = cls.requires_calibration() if hasattr(cls, "requires_calibration") else False + kw["images"] = tio.decode_cameras([i.model_dump(exclude_none=True) for i in req.images], calib, order=order, + require_calibration=require, max_bytes=max_bytes) + if calib is not None: + kw["calibration"] = calib + if req.stream is not None: + s = req.stream.model_dump(exclude_none=True) + if "T_world_from_ego" in s: + s["T_world_from_ego"] = tio.parse_transform(s["T_world_from_ego"], field="stream.T_world_from_ego") + kw["stream"] = s + if req.inputs is not None: + kw["inputs"] = tio.decode_named_arrays(req.inputs.model_dump(exclude_none=True), max_bytes=max_bytes) + if spec.decode_extra is not None: + spec.decode_extra(req, kw, max_bytes) + return kw + + +def create_app(spec: ServerSpec, *, model_factory: Optional[Callable[[Dict[str, Any]], Any]] = None) -> FastAPI: + """The ASGI app of one bundle (see the module docstring).""" + state = ServerState(spec, model_factory or default_model_factory(spec)) + RequestModel = spec.request_model + + @asynccontextmanager + async def lifespan(_app: FastAPI): + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") + cfg = config_from_env(spec) + if cfg["mesh_shape"] != (1, 1): + raise RuntimeError(f"TT_MESH_SHAPE={cfg['mesh_shape']} is a multi-chip mesh; {spec.model_name} runs on " + "exactly one Blackhole chip (mesh_device P150, shape 1x1)") + if cfg["torch_threads"]: + import torch + + torch.set_num_threads(int(cfg["torch_threads"])) + state.config, state.ready, state.error = cfg, False, None + t0 = time.perf_counter() + try: + state.model = state.model_factory(cfg) # logs: Loading weights / Opening device / Warming up / complete + except Exception as e: # startup failures exit uvicorn non-zero: no silent CPU fallback + state.error = f"{type(e).__name__}: {e}" + log.exception("startup failed") + raise + state.boot_ms = (time.perf_counter() - t0) * 1e3 + state.ready = True + log.info("%s ready in %.1f s (%s)", spec.model_name, state.boot_ms / 1e3, state.device_desc()) + try: + yield + finally: + state.ready = False + model, state.model = state.model, None + if model is not None: + log.info("Closing the model and the device") + with state.lock: + model.close() + + app = FastAPI(title=spec.model_name, version=spec.version, lifespan=lifespan, + description=spec.description or f"{spec.task} on one Tenstorrent Blackhole p150. " + "Not an OpenAI-compatible API.") + app.state.ttaw = state + + @app.middleware("http") + async def _body_limit(request: Request, call_next): + limit = (state.config or {}).get("max_body_bytes") + length = request.headers.get("content-length") + if limit and length and length.isdigit() and int(length) > limit * 4 // 3 + 4096: + return JSONResponse(status_code=400, content={"detail": f"request body of {length} bytes exceeds " + f"{spec.env_prefix}_MAX_BODY_MB"}) + return await call_next(request) + + @app.get("/") + def root() -> dict: + return {"model": spec.model_name, "routes": ["/health", "/v1/health", "/info", "/v1/models", "/predict"], + "docs": "/docs"} + + @app.get("/health") + def health() -> dict: + """Always 200: ``ok`` after warm-up, ``starting`` before, ``error`` if the boot failed.""" + return {"status": state.status(), "model": spec.model_name, "device": state.device_desc(), + "error": state.error} + + @app.get("/v1/health") + def v1_health() -> dict: # tt-model's hint for non-chat packages points here + return health() + + @app.get("/v1/models") + def v1_models() -> dict: + """OpenAI-shaped stub so tt-model's ready card / probes do not 404. This is NOT a chat API.""" + return {"object": "list", "data": [{"id": state.config.get("model_id") or spec.default_weights, + "object": "model", "owned_by": spec.owner}]} + + @app.get("/info") + def info() -> dict: + m = state.model + minfo = dict(getattr(m, "info", {}) or {}) if m is not None else {} + calib = sorted(p.stem for p in Path(spec.calib_dir).glob("*.json")) if spec.calib_dir else [] + body = { + "model": spec.model_name, "task": spec.task, "status": state.status(), "hardware": spec.hardware, + "io": spec.io, "autoware": dict(spec.autoware), + "weights": minfo.get("weights") or {"repo": state.config.get("model_id") or spec.default_weights}, + "device": state.device_desc(), "mesh_shape": os.environ.get("TT_MESH_SHAPE", "1x1"), + "input": {"kind": minfo.get("input_kind"), "point_fields": minfo.get("point_fields"), + "camera_order": minfo.get("camera_order"), "batch_size": 1, + "point_formats": list(tio.POINT_FORMATS), "max_body_bytes": state.config.get("max_body_bytes"), + "calibration_presets": calib, "extra_inputs": minfo.get("extra_inputs"), + "input_schema": minfo.get("input_schema")}, + "output": {"labels": minfo.get("labels")}, + "variant": minfo.get("variant"), "warm_variants": minfo.get("warm_variants"), + "runtime_params": minfo.get("runtime_params"), "compile_params": minfo.get("compile_params"), + "warmup_ms": minfo.get("warmup_ms"), "boot_ms": state.boot_ms, "source": dict(spec.source), + } + if spec.info_extra is not None and m is not None: + body.update(spec.info_extra(m)) + return body + + @app.post("/predict") + def predict(req: RequestModel) -> dict: + """One frame -> the model output's ``to_dict`` + ``timing_ms``. Sync handler: uvicorn runs it in a worker + thread; the lock serializes the device.""" + if not state.ready: + raise HTTPException(status_code=503, detail="model is still starting" if not state.error + else f"model failed to start: {state.error}") + model = state.model + t0 = time.perf_counter() + try: + kw = decode_request(req, spec, state.config.get("max_body_bytes") or (256 << 20)) + params = model.validate_params(req.params) + except tio.InputError as e: + raise HTTPException(status_code=400, detail=str(e)) from None + t1 = time.perf_counter() + try: + with state.lock: + out = model(**kw, **params) + except tio.InputError as e: # raised by the model's own pre-processing (shape / range checks) + raise HTTPException(status_code=400, detail=str(e)) from None + except Exception as e: # noqa: BLE001 -- a device / runtime failure + log.exception("inference failed") + raise HTTPException(status_code=500, detail=f"inference failed: {type(e).__name__}: {e}") from None + t2 = time.perf_counter() + body = out.to_dict(req.output_format) + bad = _non_finite_path(body) + if bad is not None: # strict JSON has no NaN / Infinity: say where, instead of a bare 500 from the encoder + log.error("inference produced a non-finite value at %s", bad) + raise HTTPException(status_code=500, detail=f"inference failed: non-finite value at {bad}") + timing = dict(body.get("timing_ms") or {}) + timing.update({"decode": round((t1 - t0) * 1e3, 3), "model_call": round((t2 - t1) * 1e3, 3), + "total": round((time.perf_counter() - t0) * 1e3, 3)}) + body["timing_ms"] = timing + return body + + state.predict = predict + return app diff --git a/code/tt_depthpro2/ttaw/server/client.py b/code/tt_depthpro2/ttaw/server/client.py new file mode 100644 index 0000000000000000000000000000000000000000..dbea7d078fcbe83c23ab89c714b62ede9eb19e92 --- /dev/null +++ b/code/tt_depthpro2/ttaw/server/client.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""C08 client: build / send ``POST /predict`` requests and run smoke checks. Standard library only. + +This module imports nothing from ttaw (no relative imports), so it works three ways: as ``.ttaw.server.client``, +as a script, and loaded by path from a bundle's ``smoke_test.py`` running under the host's system ``python3`` +(``container_smoke.sh``):: + + HERE = Path(__file__).resolve().parent # code//server + sys.path.insert(0, str(HERE.parent / "ttaw" / "server")) + import client as ttaw_client + +CLI:: + + python client.py --points sample.npz --out req.json # write the request + python client.py --points sample.npz --url http://127.0.0.1:20000 # send it, print the response + python client.py --image CAM_FRONT=f.jpg --calib-preset rig --url ... # cameras + python client.py --inputs scene.npz --url ... # planner +""" +from __future__ import annotations + +import argparse +import base64 +import json +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path +from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple + +__all__ = ["POINT_SUFFIXES", "b64file", "build_request", "post", "get_json", "wait_ready", "check_service", + "check_bad_request", "smoke_line", "main"] + +POINT_SUFFIXES = {".bin": "bin", ".npy": "npy", ".npz": "npz", ".pcd": "pcd"} + + +def b64file(path: Any) -> str: + return base64.b64encode(Path(path).read_bytes()).decode("ascii") + + +def build_request(points: Optional[str] = None, fields: Optional[Sequence[str]] = None, images: Iterable[str] = (), + calib: Optional[str] = None, calib_preset: Optional[str] = None, inputs: Optional[str] = None, + params: Optional[Dict[str, Any]] = None, stream_id: Optional[str] = None, reset: bool = False, + output_format: str = "json") -> Dict[str, Any]: + """A ``/predict`` body from files: ``points`` path (.bin needs ``fields``), ``images`` as ``NAME=PATH``, + ``calib`` JSON file or ``calib_preset`` name, ``inputs`` .npz (planner), ``params``, stream id / reset.""" + req: Dict[str, Any] = {} + if points: + p = Path(points) + fmt = POINT_SUFFIXES.get(p.suffix.lower()) + if fmt is None: + raise ValueError(f"points: unknown suffix {p.suffix!r} (use .bin / .npy / .npz / .pcd)") + req["points"] = {"format": fmt, "data": b64file(p)} + if fields: + req["points"]["fields"] = list(fields) + images = list(images) + if images: + req["images"] = [] + for spec in images: + name, _, path = spec.partition("=") + if not path: + raise ValueError(f"image expects NAME=PATH, got {spec!r}") + req["images"].append({"camera": name, "data": b64file(path)}) + if calib: + req["calibration"] = json.loads(Path(calib).read_text()) + elif calib_preset: + req["calibration"] = {"preset": calib_preset} + if inputs: + req["inputs"] = {"format": "npz", "data": b64file(inputs)} + if params: + req["params"] = dict(params) + if stream_id is not None or reset: + req["stream"] = {"id": stream_id or "default", "reset": bool(reset)} + if output_format != "json": + req["output_format"] = output_format + return req + + +def post(url: str, payload: Dict[str, Any], timeout: float = 120.0) -> Tuple[int, Dict[str, Any]]: + """POST ``payload`` to ``/predict`` -> ``(status, json body)`` (HTTP errors are returned, not raised).""" + data = json.dumps(payload).encode("utf-8") + r = urllib.request.Request(url.rstrip("/") + "/predict", 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 get_json(url: str, timeout: float = 10.0) -> Dict[str, Any]: + with urllib.request.urlopen(url, timeout=timeout) as r: + return json.loads(r.read().decode("utf-8")) + + +def wait_ready(base: str, wait_s: float = 0.0, poll_s: float = 5.0) -> Dict[str, Any]: + """Poll ``/health`` until ``ok`` / ``error`` or ``wait_s`` elapses; returns the last health body.""" + deadline = time.time() + wait_s + last: Dict[str, Any] = {} + while True: + try: + last = get_json(base.rstrip("/") + "/health") + if last.get("status") in ("ok", "error"): + return last + except (urllib.error.URLError, OSError, ValueError) as e: + last = {"status": f"unreachable ({e})"} + if time.time() >= deadline: + return last + time.sleep(poll_s) + + +def check_service(base: str, *, expect_dispatch: Optional[str] = "eth", + expect_grid: Optional[str] = "12x10") -> Tuple[Dict[str, Any], List[str]]: + """``/info`` and ``/v1/models`` answer; ``/info`` reports the pinned dispatch and grid (PLAN.md 0.3 item 6: + the smoke must assert ETH dispatch and 12x10, not just print them). Returns ``(info, failures)``.""" + fails: List[str] = [] + try: + info = get_json(base.rstrip("/") + "/info") + models = get_json(base.rstrip("/") + "/v1/models") + except (urllib.error.URLError, OSError, ValueError) as e: + return {}, [f"/info or /v1/models: {e}"] + if not models.get("data"): + fails.append("/v1/models is empty") + device = info.get("device") or {} + if expect_dispatch and device.get("dispatch") != expect_dispatch: + fails.append(f"dispatch is {device.get('dispatch')!r}, expected {expect_dispatch!r}") + if expect_grid and device.get("grid") != expect_grid: + fails.append(f"grid is {device.get('grid')!r}, expected {expect_grid!r}") + return info, fails + + +def check_bad_request(base: str, payload: Optional[Dict[str, Any]] = None) -> Optional[str]: + """A malformed request must answer 400 (not 500). Returns a failure message or None.""" + code, _ = post(base, payload or {"points": {"format": "npy", "data": "not base64!"}}) + return None if code == 400 else f"malformed request answered {code}, expected 400" + + +def smoke_line(model: str, summary: str, failures: Sequence[str]) -> str: + """The one-line verdict container_smoke.sh greps: ``PASS : ...`` / ``FAIL : ... :: reasons``.""" + if failures: + return f"FAIL {model}: {summary} :: " + "; ".join(list(failures)[:5]) + return f"PASS {model}: {summary}" + + +def _param(text: str) -> Tuple[str, Any]: + k, _, v = text.partition("=") + try: + return k, json.loads(v) + except ValueError: + return k, v + + +def main(argv: Optional[Sequence[str]] = None) -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--points") + ap.add_argument("--fields", help="comma list, e.g. x,y,z,intensity (needed for .bin)") + ap.add_argument("--image", action="append", default=[], help="NAME=PATH, repeat per camera") + ap.add_argument("--calib", help="calibration JSON file") + ap.add_argument("--calib-preset", help="a preset name listed by /info") + ap.add_argument("--inputs", help=".npz of named input tensors (planner)") + ap.add_argument("--param", action="append", default=[], help="k=v (JSON value), repeat") + ap.add_argument("--stream-id") + ap.add_argument("--reset", action="store_true") + ap.add_argument("--output-format", default="json", choices=["json", "npz"]) + ap.add_argument("--out", help="write the request JSON here") + ap.add_argument("--url", help="POST it to this server and print the response") + a = ap.parse_args(argv) + req = build_request(a.points, a.fields.split(",") if a.fields else None, a.image, a.calib, a.calib_preset, + a.inputs, dict(_param(p) for p in a.param), a.stream_id, a.reset, a.output_format) + if a.out: + Path(a.out).write_text(json.dumps(req)) + if a.url: + code, body = post(a.url, req) + print(json.dumps(body, indent=1)[:20000]) + return 0 if code == 200 else 1 + if not a.out: + json.dump(req, sys.stdout) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/code/tt_depthpro2/ttaw/server/smoke.py b/code/tt_depthpro2/ttaw/server/smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..ba75158cec2288b7f9ed9555a9d206da625bee6b --- /dev/null +++ b/code/tt_depthpro2/ttaw/server/smoke.py @@ -0,0 +1,482 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""C08 smoke checks beyond HTTP: does a served ``/predict`` body agree with the stored CPU-reference body of the +same sample, and does ``/info`` report what the staged tt-model package pins for the served profile. Standard +library only. + +Like :mod:`client`, this module imports nothing from ttaw, so a bundle's ``smoke_test.py`` (run by +``container_smoke.sh`` with the host's ``python3``, which has neither numpy nor the bundle) loads it by path:: + + sys.path.insert(0, str(HERE.parent / "ttaw" / "server")) # HERE = code//server + import client as ttaw_client + import smoke as ttaw_smoke + + info, fails = ttaw_client.check_service(url, expect_dispatch="eth", expect_grid="12x10") + pinned = ttaw_smoke.pinned_config(f"{staged}/tt_kernel_manifest.json", profile) + fails += ttaw_smoke.check_pinned(info, pinned, "CENTERPOINT") # /info runs what serve.env pins + ref = ttaw_smoke.find_reference(SAMPLE, pinned["profile"], info.get("variant")) + metrics, more = ttaw_smoke.compare_with_reference(body, ttaw_smoke.load_json(ref), gates={"min_recall": 0.9}) + +The stored reference is the ``to_dict()`` body of the fp32 CPU reference on the shipped sample, saved next to it as +``.reference.json``, or ``..reference.json`` / ``..reference.json`` +when the output depends on the serve profile or the model variant. Synthetic samples may give no detections, so +agreement with the reference, not a detection count, is their smoke gate (PLAN.md section 6.3). + +What is compared, by the keys of the reference body (BUNDLE_CONVENTIONS.md section 7.4): + +- ``detections``: greedy same-label matching, reference rows in descending score order; 3-D rows (``center``) + match by BEV centre distance, 2-D rows (``box_xyxy``) by IoU; gates on recall, precision and the largest score + difference of a matched pair; +- ``trajectory``: average / final displacement over the ``x`` and ``y`` columns; +- every encoded array (``ttaw.io.encode_array`` npz / npz_compressed / raw / list, ``encode_png``), e.g. + per-point ``labels``, a ``mask`` or a ``semseg`` extra: integer arrays by the fraction of equal elements, float + arrays by the largest absolute difference; +- ``model`` and ``frame_id`` must be equal. +""" +from __future__ import annotations + +import ast +import base64 +import io +import json +import math +import re +import struct +import sys +import zipfile +import zlib +from pathlib import Path +from typing import Any, Callable, Dict, List, Mapping, NamedTuple, Optional, Sequence, Tuple, Union + +__all__ = ["DEFAULT_GATES", "ARRAY_FORMATS", "Array", "load_json", "decode_array", "find_reference", + "compare_with_reference", "describe_metrics", "pinned_config", "check_pinned"] + +ARRAY_FORMATS = ("npz", "npz_compressed", "raw", "list", "png") +DEFAULT_GATES: Dict[str, Optional[float]] = { + "max_center_dist": 0.5, # 3-D detections: same-label BEV centre distance of a match (m) + "min_iou": 0.5, # 2-D detections: same-label box IoU of a match + "min_recall": 0.95, # matched / reference detections + "min_precision": 0.95, # matched / served detections + "max_score_err": 0.05, # largest |score difference| of a matched pair + "min_label_agreement": 0.99, # integer arrays (per-point labels, masks): fraction of equal elements + "max_abs_err": None, # float arrays: largest |difference| (reported only, unless set) + "max_ade": 0.5, # trajectories: average displacement over x, y (m) + "max_fde": 1.0, # trajectories: final displacement (m) +} + +PathLike = Union[str, Path] +# numpy type code (without the byte-order character) -> (struct code, numpy dtype name) +_TYPES = {"b1": ("?", "bool"), "u1": ("B", "uint8"), "u2": ("H", "uint16"), "u4": ("I", "uint32"), + "u8": ("Q", "uint64"), "i1": ("b", "int8"), "i2": ("h", "int16"), "i4": ("i", "int32"), + "i8": ("q", "int64"), "f2": ("e", "float16"), "f4": ("f", "float32"), "f8": ("d", "float64")} +_BY_NAME = {name: code for code, name in _TYPES.values()} +_SAFE_KEY = re.compile(r"[A-Za-z0-9_.-]+") + + +class Array(NamedTuple): + """A decoded array: ``values`` are the elements in C order (flattened).""" + + shape: Tuple[int, ...] + dtype: str + values: List[Any] + + @property + def is_float(self) -> bool: + return self.dtype.startswith("float") + + +def load_json(path: PathLike) -> Dict[str, Any]: + return json.loads(Path(path).read_text()) + + +# ------------------------------------------------------------------------------------------------ decoding + +def _count(shape: Sequence[int]) -> int: + n = 1 + for d in shape: + n *= int(d) + return n + + +def _fortran_to_c(values: List[Any], shape: Sequence[int]) -> List[Any]: + """Reorder column-major elements into row-major order.""" + strides, step = [], 1 + for d in shape: + strides.append(step) + step *= d + out, index = [], [0] * len(shape) + for _ in range(len(values)): + out.append(values[sum(i * s for i, s in zip(index, strides))]) + for k in range(len(shape) - 1, -1, -1): + index[k] += 1 + if index[k] < shape[k]: + break + index[k] = 0 + return out + + +def _npy(raw: bytes) -> Array: + """One ``.npy`` file (format 1.0 / 2.0 / 3.0, plain numeric dtypes).""" + if raw[:6] != b"\x93NUMPY": + raise ValueError("not an .npy file") + major = raw[6] + if major == 1: + (hlen,), start = struct.unpack("": ">", "=": "<" if sys.byteorder == "little" else ">"}.get(descr[0], "<") + code, name = _TYPES[descr[1:]] + n = _count(shape) + data = raw[start + hlen:] + size = n * struct.calcsize("<" + code) + if len(data) < size: + raise ValueError(f".npy data holds {len(data)} bytes, {size} expected") + values = list(struct.unpack(f"{order}{n}{code}", data[:size])) + if header.get("fortran_order") and len(shape) > 1: + values = _fortran_to_c(values, shape) + return Array(shape, name, values) + + +def _paeth(a: int, b: int, c: int) -> int: + p = a + b - c + pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) + if pa <= pb and pa <= pc: + return a + return b if pb <= pc else c + + +def _png(raw: bytes) -> Array: + """An 8-bit, non-interlaced grey / grey+alpha / RGB / RGBA PNG (what ``ttaw.io.encode_png`` writes).""" + if raw[:8] != b"\x89PNG\r\n\x1a\n": + raise ValueError("not a PNG file") + pos, idat, head = 8, [], None + while pos + 8 <= len(raw): + length, kind = struct.unpack(">I4s", raw[pos:pos + 8]) + chunk = raw[pos + 8:pos + 8 + length] + pos += 12 + length + if kind == b"IHDR": + head = struct.unpack(">IIBBBBB", chunk) + elif kind == b"IDAT": + idat.append(chunk) + elif kind == b"IEND": + break + if head is None: + raise ValueError("PNG without IHDR") + width, height, depth, color, _, _, interlace = head + channels = {0: 1, 2: 3, 4: 2, 6: 4}.get(color) + if depth != 8 or channels is None or interlace: + raise ValueError(f"PNG bit depth {depth}, colour type {color}, interlace {interlace} is not supported") + data = zlib.decompress(b"".join(idat)) + stride, bpp = width * channels, channels + if len(data) < height * (stride + 1): + raise ValueError("truncated PNG image data") + out, prev = bytearray(), bytearray(stride) + for y in range(height): + base = y * (stride + 1) + ftype, row = data[base], bytearray(data[base + 1:base + 1 + stride]) + if ftype == 1: + for i in range(bpp, stride): + row[i] = (row[i] + row[i - bpp]) & 0xFF + elif ftype == 2: + for i in range(stride): + row[i] = (row[i] + prev[i]) & 0xFF + elif ftype == 3: + for i in range(stride): + left = row[i - bpp] if i >= bpp else 0 + row[i] = (row[i] + ((left + prev[i]) >> 1)) & 0xFF + elif ftype == 4: + for i in range(stride): + left, upper_left = (row[i - bpp], prev[i - bpp]) if i >= bpp else (0, 0) + row[i] = (row[i] + _paeth(left, prev[i], upper_left)) & 0xFF + elif ftype != 0: + raise ValueError(f"PNG filter type {ftype} is invalid") + out += row + prev = row + shape = (height, width) if channels == 1 else (height, width, channels) + return Array(shape, "uint8", list(out)) + + +def _flatten(value: Any, out: List[Any]) -> List[Any]: + if isinstance(value, list): + for v in value: + _flatten(v, out) + else: + out.append(value) + return out + + +def decode_array(spec: Mapping[str, Any]) -> Array: + """Decode an encoded output array ``{"format", "key", "dtype", "shape", "data"}`` (``ttaw.io.encode_array`` / + ``encode_png``) without numpy. Raises ``ValueError`` for anything it cannot decode.""" + fmt = spec.get("format") + if fmt not in ARRAY_FORMATS: + raise ValueError(f"array format {fmt!r} is not one of {ARRAY_FORMATS}") + if fmt == "list": + dtype = str(spec.get("dtype") or "float64") + arr = Array(tuple(int(d) for d in spec.get("shape") or ()), dtype, _flatten(spec.get("data"), [])) + else: + raw = base64.b64decode(spec.get("data") or "") + if fmt == "png": + arr = _png(raw) + elif fmt == "raw": + dtype = str(spec.get("dtype")) + if dtype not in _BY_NAME: + raise ValueError(f"raw array dtype {dtype!r} is not supported") + shape = tuple(int(d) for d in spec.get("shape") or ()) + n, code = _count(shape), _BY_NAME[dtype] + if len(raw) != n * struct.calcsize("<" + code): + raise ValueError(f"raw array holds {len(raw)} bytes, shape {list(shape)} {dtype} needs " + f"{n * struct.calcsize('<' + code)}") + arr = Array(shape, dtype, list(struct.unpack(f"<{n}{code}", raw))) + else: + with zipfile.ZipFile(io.BytesIO(raw)) as z: + names = z.namelist() + member = f"{spec.get('key')}.npy" + if member not in names: + if len(names) != 1: + raise ValueError(f"npz has no member {member!r} (members {names})") + member = names[0] + arr = _npy(z.read(member)) + if "shape" in spec and list(arr.shape) != [int(d) for d in spec["shape"]]: + raise ValueError(f"decoded shape {list(arr.shape)} differs from the declared {list(spec['shape'])}") + if len(arr.values) != _count(arr.shape): + raise ValueError(f"{len(arr.values)} elements do not fill shape {list(arr.shape)}") + return arr + + +def _is_encoded_array(value: Any) -> bool: + return isinstance(value, Mapping) and value.get("format") in ARRAY_FORMATS and "data" in value + + +# ---------------------------------------------------------------------------------------------- comparison + +def find_reference(sample: PathLike, *keys: Optional[str]) -> Optional[Path]: + """The stored CPU-reference body of ``sample``: the first existing ``..reference.json`` for the + given keys (e.g. the serve profile, then the model variant), else ``.reference.json``; None if absent.""" + p = Path(sample) + names = [f"{p.stem}.{k}.reference.json" for k in keys if k and _SAFE_KEY.fullmatch(str(k))] + for name in names + [f"{p.stem}.reference.json"]: + if (p.parent / name).is_file(): + return p.parent / name + return None + + +def _label(row: Mapping[str, Any]) -> Any: + return row.get("label_id", row.get("label")) + + +def _iou(a: Sequence[float], b: Sequence[float]) -> float: + ix = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) + iy = max(0.0, min(a[3], b[3]) - max(a[1], b[1])) + inter = ix * iy + union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter + return inter / union if union > 0 else 0.0 + + +def _greedy_match(test: List[Mapping[str, Any]], ref: List[Mapping[str, Any]], + cost: Callable[[Mapping[str, Any], Mapping[str, Any]], float], + accept: Callable[[float], bool]) -> List[Tuple[int, int, float]]: + """Reference rows in descending score order (stable) each take the cheapest unused same-label test row; + returns ``(test index, reference index, cost)`` of the accepted pairs.""" + used = [False] * len(test) + pairs = [] + for i in sorted(range(len(ref)), key=lambda k: -float(ref[k].get("score", 0.0))): + best, best_cost = -1, math.inf + for j, row in enumerate(test): + if not used[j] and _label(row) == _label(ref[i]): + c = cost(row, ref[i]) + if c < best_cost: + best, best_cost = j, c + if best >= 0 and accept(best_cost): + used[best] = True + pairs.append((best, i, best_cost)) + return pairs + + +def _compare_detections(test: Any, ref: List[Mapping[str, Any]], + g: Mapping[str, Any]) -> Tuple[Dict[str, Any], List[str]]: + if not isinstance(test, list): + return {}, ["the response has no 'detections' list"] + rows = ref + test + if any("center" in d for d in rows): + kind = "3d" + pairs = _greedy_match(test, ref, lambda t, r: math.hypot(t["center"][0] - r["center"][0], + t["center"][1] - r["center"][1]), + lambda c: c <= g["max_center_dist"]) + elif any("box_xyxy" in d for d in rows): + kind = "2d" + pairs = _greedy_match(test, ref, lambda t, r: 1.0 - _iou(t["box_xyxy"], r["box_xyxy"]), + lambda c: 1.0 - c >= g["min_iou"]) + elif not rows: # nothing detected on either side (e.g. a synthetic sample): agreement + kind, pairs = "none", [] + else: + return {}, ["detections carry neither 'center' nor 'box_xyxy'"] + score_err = max((abs(float(test[j]["score"]) - float(ref[i]["score"])) for j, i, _ in pairs), default=0.0) + m: Dict[str, Any] = {"kind": kind, "n": len(test), "n_ref": len(ref), "matched": len(pairs), + "recall": len(pairs) / len(ref) if ref else 1.0, + "precision": len(pairs) / len(test) if test else 1.0, "score_err_max": score_err} + if kind == "3d": + m["center_err_max"] = max((c for _, _, c in pairs), default=0.0) + elif kind == "2d": + m["iou_min"] = min((1.0 - c for _, _, c in pairs), default=1.0) + fails = [] + if m["recall"] < g["min_recall"]: + fails.append(f"detections recall {m['recall']:.3f} < {g['min_recall']} ({len(pairs)}/{len(ref)} reference " + "detections matched)") + if m["precision"] < g["min_precision"]: + fails.append(f"detections precision {m['precision']:.3f} < {g['min_precision']} ({len(pairs)}/{len(test)} " + "served detections matched)") + if score_err > g["max_score_err"]: + fails.append(f"detections max |score difference| {score_err:.4f} > {g['max_score_err']}") + return m, fails + + +def _compare_trajectory(body: Mapping[str, Any], ref: Mapping[str, Any], + g: Mapping[str, Any]) -> Tuple[Dict[str, Any], List[str]]: + test, want = body.get("trajectory"), ref["trajectory"] + if not isinstance(test, list): + return {}, ["the response has no 'trajectory'"] + if len(test) != len(want): + return {"n": len(test), "n_ref": len(want)}, [f"trajectory has {len(test)} poses, the reference {len(want)}"] + columns = list(ref.get("columns") or ["x", "y"]) + if body.get("columns", columns) != columns: + return {}, [f"trajectory columns {body.get('columns')} differ from the reference {columns}"] + ix, iy = (columns.index("x"), columns.index("y")) if {"x", "y"} <= set(columns) else (0, 1) + disp = [math.hypot(a[ix] - b[ix], a[iy] - b[iy]) for a, b in zip(test, want)] + m = {"n": len(test), "ade": sum(disp) / len(disp) if disp else 0.0, "fde": disp[-1] if disp else 0.0} + fails = [] + if not m["ade"] <= g["max_ade"]: + fails.append(f"trajectory ADE {m['ade']:.4f} > {g['max_ade']}") + if not m["fde"] <= g["max_fde"]: + fails.append(f"trajectory FDE {m['fde']:.4f} > {g['max_fde']}") + return m, fails + + +def _compare_array(name: str, test: Any, ref: Mapping[str, Any], + g: Mapping[str, Any]) -> Tuple[Dict[str, Any], List[str]]: + if not _is_encoded_array(test): + return {}, [f"the response has no encoded array {name!r}"] + a, b = decode_array(test), decode_array(ref) + if a.shape != b.shape: + return {"shape": list(a.shape), "shape_ref": list(b.shape)}, [ + f"{name}: shape {list(a.shape)} differs from the reference {list(b.shape)}"] + if a.is_float or b.is_float: + err = 0.0 + for x, y in zip(a.values, b.values): + if x == y: # equal values, equal infinities included + continue + d = abs(float(x) - float(y)) + if d != d: # NaN on either side + err = math.nan + break + err = max(err, d) + limit = g["max_abs_err"] + fails = [f"{name}: max |difference| {err:.6g} > {limit}"] if limit is not None and not err <= limit else [] + return {"max_abs_err": err, "n": len(b.values)}, fails + equal = sum(1 for x, y in zip(a.values, b.values) if x == y) + agreement = equal / len(b.values) if b.values else 1.0 + fails = [] + if agreement < g["min_label_agreement"]: + fails.append(f"{name}: agreement {agreement:.4f} < {g['min_label_agreement']} " + f"({len(b.values) - equal} of {len(b.values)} elements differ)") + return {"agreement": agreement, "n": len(b.values)}, fails + + +def compare_with_reference(body: Mapping[str, Any], reference: Mapping[str, Any], + gates: Optional[Mapping[str, Optional[float]]] = None + ) -> Tuple[Dict[str, Dict[str, Any]], List[str]]: + """Compare a served ``/predict`` body with the stored CPU-reference body of the same input (module docstring). + ``gates`` override :data:`DEFAULT_GATES` (unknown names raise ``ValueError``). Returns ``(metrics per compared + key, failures)``; a body that cannot be decoded is a failure, not an exception.""" + unknown = sorted(set(gates or {}) - set(DEFAULT_GATES)) + if unknown: + raise ValueError(f"unknown reference gates {unknown}; known: {sorted(DEFAULT_GATES)}") + g = {**DEFAULT_GATES, **dict(gates or {})} + metrics: Dict[str, Dict[str, Any]] = {} + fails = [f"{k} is {body.get(k)!r}, the reference has {reference[k]!r}" for k in ("model", "frame_id") + if k in reference and body.get(k) != reference[k]] + checks: List[Tuple[str, Callable[[], Tuple[Dict[str, Any], List[str]]]]] = [] + if "detections" in reference: + checks.append(("detections", lambda: _compare_detections(body.get("detections"), reference["detections"], g))) + if "trajectory" in reference: + checks.append(("trajectory", lambda: _compare_trajectory(body, reference, g))) + for key, value in reference.items(): + if key != "arrays" and _is_encoded_array(value): + checks.append((key, lambda k=key, v=value: _compare_array(k, body.get(k), v, g))) + if not checks: + fails.append("the reference holds nothing to compare (no detections, trajectory or encoded arrays)") + for key, check in checks: + try: + metrics[key], more = check() + except (ValueError, KeyError, TypeError, IndexError, struct.error, zlib.error, zipfile.BadZipFile) as e: + metrics[key], more = {}, [f"{key}: cannot compare ({type(e).__name__}: {e})"] + fails += more + return metrics, fails + + +def describe_metrics(metrics: Mapping[str, Mapping[str, Any]]) -> str: + """One compact line for the smoke verdict, e.g. ``detections 5/5 recall=1.000 precision=1.000 dscore=0.0040``.""" + parts = [] + for key, m in metrics.items(): + if "recall" in m: + parts.append(f"{key} {m['matched']}/{m['n_ref']} recall={m['recall']:.3f} " + f"precision={m['precision']:.3f} dscore={m['score_err_max']:.4f}") + elif "ade" in m: + parts.append(f"{key} ade={m['ade']:.4f} fde={m['fde']:.4f}") + elif "agreement" in m: + parts.append(f"{key} agree={m['agreement']:.4f}") + elif "max_abs_err" in m: + parts.append(f"{key} max_abs={m['max_abs_err']:.4g}") + else: + parts.append(f"{key} -") + return "; ".join(parts) or "-" + + +# ----------------------------------------------------------------------------------------- package pins + +def pinned_config(manifest: PathLike, profile: Optional[str] = None) -> Dict[str, Any]: + """What a staged package (``//tt_kernel_manifest.json``) pins for one serve profile (default: the + package's default profile): ``{"profile": name, "env": serve.env with the profile's env on top (tt-model's + merge rule), "weights": {"repo", "revision"}}``.""" + m = load_json(manifest) + c = m.get("container") or {} + profiles = c.get("serve_profiles") or [{"name": "default", "env": {}}] + name = profile or c.get("default_profile") or profiles[0].get("name") + chosen = [p for p in profiles if p.get("name") == name] + if not chosen: + raise ValueError(f"no serve profile {name!r} in {manifest}; available: {[p.get('name') for p in profiles]}") + env = dict((c.get("serve") or {}).get("env") or {}) + env.update({k: v for k, v in (chosen[0].get("env") or {}).items() if v is not None}) + weights = m.get("weights") or {} + return {"profile": name, "env": {k: str(v) for k, v in env.items()}, + "weights": {"repo": weights.get("repo_id"), "revision": weights.get("revision")}} + + +def check_pinned(info: Mapping[str, Any], pinned: Mapping[str, Any], prefix: str) -> List[str]: + """``/info`` runs what the package pins: ``_DISPATCH`` (eth | worker), ``_NUM_CQS``, + ``_VARIANT`` and the weights revision. Pins that are absent are not checked. Returns failures.""" + env = pinned.get("env") or {} + device = info.get("device") or {} + profile = pinned.get("profile") + fails = [] + dispatch = (env.get(f"{prefix}_DISPATCH") or "").strip().lower() + if dispatch in ("eth", "worker") and device.get("dispatch") != dispatch: + fails.append(f"dispatch is {device.get('dispatch')!r}, profile {profile!r} pins {prefix}_DISPATCH={dispatch}") + cqs = (env.get(f"{prefix}_NUM_CQS") or "").strip() + if cqs and str(device.get("num_command_queues")) != cqs: + fails.append(f"num_command_queues is {device.get('num_command_queues')!r}, profile {profile!r} pins " + f"{prefix}_NUM_CQS={cqs}") + variant = (env.get(f"{prefix}_VARIANT") or "").strip() + if variant and info.get("variant") != variant: + fails.append(f"variant is {info.get('variant')!r}, profile {profile!r} pins {prefix}_VARIANT={variant}") + revision = (pinned.get("weights") or {}).get("revision") + served = (info.get("weights") or {}).get("revision") + if revision and served != revision: + fails.append(f"weights revision is {served!r}, the package pins {revision!r}") + return fails diff --git a/code/tt_depthpro2/ttaw/sparse.py b/code/tt_depthpro2/ttaw/sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..09a9d3aa5447b6dfc5a45780b874d9a061dad9b7 --- /dev/null +++ b/code/tt_depthpro2/ttaw/sparse.py @@ -0,0 +1,421 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C13 sparse rulebooks: spconv-faithful neighbour maps of sparse 3-D convolutions, built on the host, in the +*gather* form the device consumes (PLAN.md section 1.2 row C13; owned by the BEVFusion port; S:bevfusion:465-466, +S:ptv3:158). + +A sparse tensor is a set of active voxels ``coords (N, 3)`` = ``(x, y, z)`` (batch 0 implied) in a grid of +``spatial_shape (X, Y, Z)``. Every sparse conv of the Autoware graphs (``autoware::GetIndicePairsImplicitGemm`` + +``ImplicitGemm``, spconv 2.3.8 ``MaskImplicitGemm``) is, per output voxel ``o``, + + out[o] = sum_k W[:, k, :] @ in[ nmap[o, k] ] (taps with ``nmap[o, k] == -1`` contribute nothing) + +with ``W`` the KRSC filter ``[Cout, k0, k1, k2, Cin]`` (``k0`` along x, ``k1`` along y, ``k2`` along z) and the tap +index ``k = (a * k1 + b) * k2 + c`` (row-major over (x, y, z), spconv's ``layout_rs``). This module builds +``nmap`` -- a pure gather table, no scatter, for sub-manifold and strided layers alike -- and the device-side index +forms of it: + +- :class:`SparseLevel`: the active set of one resolution with a hashed lookup (sorted int64 keys + ``searchsorted``; + keys are exact for any coordinate, also outside the grid); +- :func:`subm_neighbor_map`: sub-manifold conv (output set == input set; spconv uses ``padding = (k // 2) * + dilation`` whatever the attribute says, ``spconv/csrc/sparse/indices.py:1522``). ``rule="spconv"`` (default) + reproduces spconv's **13-query + symmetric-write** construction (``generate_subm_conv_inds`` launches only the taps + ``k <= K // 2``, ``indices.py:1532``; a hit also writes the mirrored pair ``pair[K-1-k][in] = out``, ``:865``; the + centre is always the voxel itself, ``:838-845``). Its bounds check is applied to the *queried* coordinate, so a tap + ``k < K // 2`` is accepted only if the **neighbour** lies inside the grid and a tap ``k > K // 2`` only if the + **output voxel** does (the asymmetric-bounds rule of S:ptv3:158, verified bit-exact against spconv there). For + voxel sets inside the grid (every BEVFusion level) it equals ``rule="exact"``, the plain 27-tap lookup; +- :func:`strided_neighbor_map`: regular (strided) sparse conv: output ``o`` is active iff some active input ``i`` + and tap ``k`` give ``i = o * s - p + k * d`` with ``0 <= o < out_shape`` (spconv ``generate_conv_inds``); outputs + come in ascending linear-key order (any order is equivalent: the next layers are permutation-equivariant); one + input per (output, tap), so the strided layer is a gather too; +- device forms (C28, probe P4): :func:`gather_index` (``-1`` -> an explicit zero sentinel row, capacity padding), + :func:`im2col_index` (the **tile-ordered** index of the one-gather im2col: ``(voxel block of 32, tap, voxel)``, + so ``ttnn.embedding(..., layout=TILE)`` of a ``[N/32, K * 32]`` index into a ``Cin % 32 == 0`` table gives a tensor + whose tile sequence *is* the ``[N, K * Cin]`` im2col matrix, read through ``ttnn.experimental.view``) and its + oracle :func:`im2col_numpy`; :func:`dense_gather_index` (to-dense as a gather: one ``[X * Y]`` canvas index per z + slice); +- capacities (PLAN.md 0.2: grid-independent constants chosen from data): :func:`select_capacity` picks the smallest + bucket that holds a count, and flags an overflow; +- oracles: :func:`sparse_conv_numpy` (the gather form above, float64 accumulation) and :func:`dense_conv3d_numpy` (a + brute-force dense 3-D cross-correlation restricted to the active outputs; spconv == dense Conv3d on the active set). + +Not here yet (their consumer adds them, PTv3): the linear-key **alias** mode of S:ptv3:388-393 (spconv inserts +out-of-grid voxels under aliasing int32 keys; ``rule="alias"`` raises ``NotImplementedError``) and Morton / +serialization helpers. + +numpy only; no side effects on import. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Dict, Iterable, Optional, Sequence, Tuple + +import numpy as np + +__all__ = [ + "SparseLevel", + "RULES", + "kernel_offsets", + "conv_out_shape", + "subm_neighbor_map", + "strided_neighbor_map", + "pairs_count", + "gather_index", + "im2col_index", + "im2col_numpy", + "dense_gather_index", + "dense_numpy", + "select_capacity", + "sparse_conv_numpy", + "dense_conv3d_numpy", + "TILE_ROWS", + "neighbor_stats", + "iter_taps", +] + +RULES = ("spconv", "exact") # subm neighbour rules ("alias": PTv3, not implemented yet) +TILE_ROWS = 32 # rows of one ttnn tile: the voxel block of the tile-ordered im2col index + + +def _triple(v: Any, name: str) -> Tuple[int, int, int]: + if isinstance(v, (int, np.integer)): + t = (int(v),) * 3 + else: + t = tuple(int(x) for x in v) + if len(t) != 3: + raise ValueError(f"{name} needs 3 values, got {v!r}") + return t # type: ignore[return-value] + + +# ------------------------------------------------------------------------------------------------- levels + +@dataclass +class SparseLevel: + """The active voxels of one resolution: ``coords`` int64 ``(N, 3)`` ``(x, y, z)`` in ``spatial_shape (X, Y, Z)``. + + Rows are the feature rows of the level (row ``i`` holds voxel ``coords[i]``). Coordinates outside the grid are + allowed (spconv carries them, S:ptv3:158); keys are exact for them (no aliasing). Duplicate coordinates are + refused (a spconv indice set is unique).""" + + coords: np.ndarray + spatial_shape: Tuple[int, int, int] + + def __post_init__(self) -> None: + c = np.asarray(self.coords) + if c.ndim != 2 or c.shape[1] != 3: + raise ValueError(f"coords must be (N, 3) (x, y, z), got {c.shape}") + if c.size and not np.issubdtype(c.dtype, np.integer): + raise ValueError(f"coords must be integers, got {c.dtype}") + self.coords = np.ascontiguousarray(c, dtype=np.int64) + self.spatial_shape = _triple(self.spatial_shape, "spatial_shape") + if min(self.spatial_shape) <= 0: + raise ValueError(f"spatial_shape must be positive, got {self.spatial_shape}") + keys = self.keys_of(self.coords) + order = np.argsort(keys, kind="stable") + self._sorted = keys[order] + self._perm = order + if len(self._sorted) > 1 and np.any(self._sorted[1:] == self._sorted[:-1]): + raise ValueError("coords hold duplicate voxels") + + # exact keys over the bounding box of the grid and the voxels, widened by a margin, so no coordinate aliases + _MARGIN = 8 + + def _box(self) -> Tuple[np.ndarray, np.ndarray]: + box = getattr(self, "_box_cache", None) + if box is None: + shape = np.asarray(self.spatial_shape, dtype=np.int64) + lo, hi = np.zeros(3, np.int64), shape.copy() + if len(self.coords): + lo = np.minimum(lo, self.coords.min(axis=0)) + hi = np.maximum(hi, self.coords.max(axis=0) + 1) + box = (lo - self._MARGIN, hi + self._MARGIN) + self._box_cache = box + return box + + def keys_of(self, q: np.ndarray) -> np.ndarray: + """Exact int64 keys of ``q (M, 3)``; coordinates outside the widened bounding box get key -1 (never found: + no voxel of the level lies there).""" + q = np.asarray(q, dtype=np.int64).reshape(-1, 3) + lo, hi = self._box() + dims = hi - lo + ok = np.all((q >= lo) & (q < hi), axis=1) + r = q - lo + k = (r[:, 0] * dims[1] + r[:, 1]) * dims[2] + r[:, 2] + return np.where(ok, k, -1) + + @property + def num_active(self) -> int: + return int(len(self.coords)) + + def in_grid(self, q: Optional[np.ndarray] = None) -> np.ndarray: + """``0 <= q < spatial_shape`` on every axis (default: the level's own coords).""" + q = self.coords if q is None else np.asarray(q, dtype=np.int64) + return np.all((q >= 0) & (q < np.asarray(self.spatial_shape, dtype=np.int64)), axis=1) + + def lookup(self, q: np.ndarray) -> np.ndarray: + """Rows of the voxels at ``q (M, 3)`` (int64), ``-1`` where no active voxel is.""" + keys = self.keys_of(q) + if len(self._sorted) == 0: + return np.full(len(keys), -1, np.int64) + pos = np.searchsorted(self._sorted, keys).clip(max=len(self._sorted) - 1) + found = (self._sorted[pos] == keys) & (keys >= 0) + return np.where(found, self._perm[pos], -1) + + def linear_index(self, order: str = "xyz") -> np.ndarray: + """In-grid linear index of every voxel: ``(x * Y + y) * Z + z`` (``"xyz"``, spconv's for batch 0).""" + if order != "xyz": + raise ValueError("only the xyz order is defined") + X, Y, Z = self.spatial_shape + c = self.coords + return (c[:, 0] * Y + c[:, 1]) * Z + c[:, 2] + + def describe(self) -> Dict[str, Any]: + return {"num_active": self.num_active, "spatial_shape": list(self.spatial_shape), + "out_of_grid": int((~self.in_grid()).sum()) if self.num_active else 0} + + +# ---------------------------------------------------------------------------------------------- rulebooks + +def kernel_offsets(kernel: Any = 3, dilation: Any = 1) -> np.ndarray: + """``(K, 3)`` int64 tap offsets ``(a * d0, b * d1, c * d2)`` in tap order ``k = (a * k1 + b) * k2 + c``.""" + k = _triple(kernel, "kernel") + d = _triple(dilation, "dilation") + a, b, c = np.meshgrid(np.arange(k[0]), np.arange(k[1]), np.arange(k[2]), indexing="ij") + return np.stack([a.ravel() * d[0], b.ravel() * d[1], c.ravel() * d[2]], axis=1).astype(np.int64) + + +def conv_out_shape(spatial_shape: Any, kernel: Any, stride: Any, padding: Any, dilation: Any = 1 + ) -> Tuple[int, int, int]: + """spconv / Conv3d output grid: ``(in + 2 p - d (k - 1) - 1) // s + 1`` per axis.""" + s_in, k, s, p, d = (np.asarray(_triple(v, n)) for v, n in ((spatial_shape, "spatial_shape"), (kernel, "kernel"), + (stride, "stride"), (padding, "padding"), + (dilation, "dilation"))) + out = (s_in + 2 * p - d * (k - 1) - 1) // s + 1 + if np.any(out <= 0): + raise ValueError(f"empty output grid {tuple(out)}") + return tuple(int(v) for v in out) # type: ignore[return-value] + + +def subm_neighbor_map(level: SparseLevel, kernel: Any = 3, dilation: Any = 1, *, rule: str = "spconv") -> np.ndarray: + """Sub-manifold conv neighbour map ``(N, K)`` int32: ``nmap[o, k]`` = the input row read by tap ``k`` of output + ``o`` (the level's own rows), ``-1`` if none (module docstring for ``rule``).""" + if rule == "alias": + raise NotImplementedError("the linear-key alias mode (S:ptv3:388-393) is added by the PTv3 port") + if rule not in RULES: + raise ValueError(f"rule must be one of {RULES}") + k = _triple(kernel, "kernel") + if any(v % 2 == 0 for v in k): + raise ValueError(f"sub-manifold kernels are odd, got {k}") + d = np.asarray(_triple(dilation, "dilation"), dtype=np.int64) + pad = (np.asarray(k, dtype=np.int64) // 2) * d + offs = kernel_offsets(k, d) - pad # (K, 3) centred offsets + K = len(offs) + n = level.num_active + out = np.full((n, K), -1, dtype=np.int32) + if n == 0: + return out + c = level.coords + q = (c[:, None, :] + offs[None, :, :]).reshape(-1, 3) + rows = level.lookup(q).reshape(n, K) + if rule == "spconv": + centre = K // 2 + own_in = level.in_grid() # (N,) + nb_in = level.in_grid(q).reshape(n, K) + low = np.arange(K) < centre + accept = np.where(low[None, :], nb_in, own_in[:, None]) + rows = np.where(accept, rows, -1) + rows[:, centre] = np.arange(n) # the centre tap is the voxel itself + out[:] = rows + return out + + +def strided_neighbor_map(level: SparseLevel, kernel: Any, stride: Any, padding: Any, dilation: Any = 1 + ) -> Tuple[SparseLevel, np.ndarray]: + """Regular sparse conv: ``(out_level, nmap (N_out, K) int32)``; ``nmap[o, k]`` = the input row with + ``i = o * s - p + k * d`` (``-1``: none). Output voxels in ascending ``(x, y, z)`` linear-key order. The input + voxels must lie inside their grid (out-of-grid inputs would change spconv's set; refused).""" + k = _triple(kernel, "kernel") + s = np.asarray(_triple(stride, "stride"), dtype=np.int64) + p = np.asarray(_triple(padding, "padding"), dtype=np.int64) + d = np.asarray(_triple(dilation, "dilation"), dtype=np.int64) + out_shape = conv_out_shape(level.spatial_shape, k, s, p, d) + if level.num_active and not level.in_grid().all(): + raise ValueError("strided rulebooks need every input voxel inside its grid") + offs = kernel_offsets(k, d) # (K, 3), uncentred: tap k at + k * d + K = len(offs) + c = level.coords + num = c[:, None, :] + p - offs[None, :, :] # = o * s for a hit + ok = np.all(num % s == 0, axis=2) + o = num // s + ok &= np.all((o >= 0) & (o < np.asarray(out_shape, dtype=np.int64)), axis=2) + ii, kk = np.nonzero(ok) + oc = o[ii, kk] + X, Y, Z = out_shape + okey = (oc[:, 0] * Y + oc[:, 1]) * Z + oc[:, 2] + uniq, inv = np.unique(okey, return_inverse=True) + out_coords = np.stack([uniq // (Y * Z), (uniq // Z) % Y, uniq % Z], axis=1).astype(np.int64) + out_level = SparseLevel(out_coords, out_shape) + nmap = np.full((len(uniq), K), -1, dtype=np.int32) + nmap[inv.reshape(-1), kk] = ii # one input per (output, tap) + return out_level, nmap + + +def pairs_count(nmap: np.ndarray) -> int: + """Number of (input, output, tap) pairs of a neighbour map (the rulebook size; FLOPs = 2 Cin Cout pairs).""" + return int(np.count_nonzero(np.asarray(nmap) >= 0)) + + +# ------------------------------------------------------------------------------------------- device forms + +def gather_index(nmap: np.ndarray, *, sentinel: int, rows: Optional[int] = None) -> np.ndarray: + """``(rows, K)`` uint32: ``nmap`` with ``-1`` -> ``sentinel`` (the zero row of the feature table) and the rows + past ``len(nmap)`` (capacity padding) all ``sentinel``. ``sentinel`` must exceed every valid row.""" + nm = np.asarray(nmap) + n, K = nm.shape + rows = n if rows is None else int(rows) + if rows < n: + raise ValueError(f"{n} active rows exceed the capacity {rows}") + if n and nm.max() >= sentinel: + raise ValueError(f"row {int(nm.max())} >= sentinel {sentinel}") + if sentinel < 0 or sentinel >= 2 ** 32: + raise ValueError("sentinel must fit uint32") + out = np.full((rows, K), sentinel, dtype=np.uint32) + out[:n] = np.where(nm >= 0, nm, sentinel).astype(np.uint32) + return out + + +def im2col_index(nmap: np.ndarray, *, sentinel: int, rows: Optional[int] = None, block: int = TILE_ROWS + ) -> np.ndarray: + """The tile-ordered index of the one-gather im2col (C28, probe P4): ``(rows / block, K * block)`` uint32 with + ``index[b, k * block + v] = gather_index[b * block + v, k]``. ``ttnn.embedding`` of it into a ``[1, 1, V, Cin]`` + table (``Cin % 32 == 0``) with ``layout=TILE`` yields ``[rows / block, K * block, Cin]``, whose tiles, in memory + order, are those of the ``[rows, K * Cin]`` im2col matrix (row ``o``: the ``K`` tap rows of output ``o`` + concatenated). ``rows`` (default ``len(nmap)`` rounded up) must be a multiple of ``block``.""" + nm = np.asarray(nmap) + n, K = nm.shape + rows = -(-n // block) * block if rows is None else int(rows) + if rows % block: + raise ValueError(f"rows {rows} is not a multiple of the block {block}") + g = gather_index(nm, sentinel=sentinel, rows=rows) # (rows, K) + return np.ascontiguousarray(g.reshape(rows // block, block, K).transpose(0, 2, 1).reshape(rows // block, + K * block)) + + +def im2col_numpy(table: np.ndarray, index: np.ndarray, *, kernel_volume: int, block: int = TILE_ROWS) -> np.ndarray: + """Oracle of the device im2col: the ``[rows, K * C]`` matrix that :func:`im2col_index` describes, built from the + row table ``(V, C)`` (``index`` values are rows of ``table``).""" + t = np.asarray(table) + idx = np.asarray(index, dtype=np.int64) + nb = idx.shape[0] + K = int(kernel_volume) + if idx.shape[1] != K * block: + raise ValueError(f"index has {idx.shape[1]} columns, expected {K} x {block}") + g = idx.reshape(nb, K, block).transpose(0, 2, 1).reshape(nb * block, K) # back to (rows, K) + return t[g].reshape(nb * block, K * t.shape[1]) + + +def dense_gather_index(level: SparseLevel, *, sentinel: int, split_axis: int = 2) -> np.ndarray: + """To-dense as gathers: ``(S, A * B)`` uint32 with ``index[s, a * B + b]`` = the row of voxel at ``(a, b)`` in + slice ``s`` of ``split_axis`` (the two other axes in (x, y, z) order give ``a``, ``b``), ``sentinel`` where the + cell is empty. BEVFusion's to-dense: ``split_axis = 2`` (z), ``index[z, x * Y + y]``; the slices are concatenated + or interleaved on the channel axis afterwards.""" + if split_axis not in (0, 1, 2): + raise ValueError("split_axis must be 0, 1 or 2") + if level.num_active and not level.in_grid().all(): + raise ValueError("to-dense needs every voxel inside the grid") + if level.num_active and level.num_active > sentinel: + raise ValueError("sentinel must not be a valid row") + axes = [a for a in range(3) if a != split_axis] + S = level.spatial_shape[split_axis] + A, B = level.spatial_shape[axes[0]], level.spatial_shape[axes[1]] + out = np.full((S, A * B), sentinel, dtype=np.uint32) + c = level.coords + out[c[:, split_axis], c[:, axes[0]] * B + c[:, axes[1]]] = np.arange(level.num_active, dtype=np.uint32) + return out + + +def dense_numpy(features: np.ndarray, level: SparseLevel) -> np.ndarray: + """``(X, Y, Z, C)`` dense tensor of the level's features (zeros elsewhere): ONNX ``ScatterND`` into + ``[X, Y, Z, C]``, the reference of the to-dense gathers.""" + f = np.asarray(features) + X, Y, Z = level.spatial_shape + out = np.zeros((X, Y, Z, f.shape[1]), dtype=f.dtype) + c = level.coords + out[c[:, 0], c[:, 1], c[:, 2]] = f[: level.num_active] + return out + + +# ------------------------------------------------------------------------------------------------ capacity + +def select_capacity(count: int, buckets: Sequence[int]) -> Tuple[int, bool]: + """The smallest bucket ``>= count`` and ``False``; the largest bucket and ``True`` (overflow: the caller keeps + that many and flags the frame) when none holds it. Buckets are grid-independent constants (PLAN.md 0.2).""" + b = sorted(int(v) for v in buckets) + if not b or b[0] <= 0: + raise ValueError("buckets must be positive") + for v in b: + if count <= v: + return v, False + return b[-1], True + + +# ------------------------------------------------------------------------------------------------- oracles + +def sparse_conv_numpy(features: np.ndarray, nmap: np.ndarray, weight: np.ndarray, bias: Optional[np.ndarray] = None, + *, dtype: Any = np.float64) -> np.ndarray: + """The gather form of the sparse conv: ``out[o] = sum_k W[:, k, :] @ features[nmap[o, k]] (+ bias)``. + ``weight`` KRSC ``[Cout, k0, k1, k2, Cin]``; accumulation in ``dtype`` (float64 default).""" + f = np.asarray(features, dtype=dtype) + w = np.asarray(weight, dtype=dtype) + cout, cin = w.shape[0], w.shape[-1] + wk = w.reshape(cout, -1, cin) # (Cout, K, Cin) + nm = np.asarray(nmap) + out = np.zeros((len(nm), cout), dtype=dtype) + for k in range(nm.shape[1]): + sel = nm[:, k] >= 0 + if sel.any(): + out[sel] += f[nm[sel, k]] @ wk[:, k, :].T + if bias is not None: + out += np.asarray(bias, dtype=dtype) + return out + + +def dense_conv3d_numpy(features: np.ndarray, level: SparseLevel, weight: np.ndarray, out_coords: np.ndarray, *, + stride: Any = 1, padding: Any = 0, dilation: Any = 1) -> np.ndarray: + """Brute-force dense 3-D cross-correlation (``torch.nn.Conv3d`` semantics, zero padding) of the densified input, + read at ``out_coords``: the definition a sparse conv must equal on its active outputs. Float64; small grids.""" + w = np.asarray(weight, dtype=np.float64) + k = w.shape[1:4] + s = np.asarray(_triple(stride, "stride")) + p = np.asarray(_triple(padding, "padding")) + d = np.asarray(_triple(dilation, "dilation")) + X, Y, Z = level.spatial_shape + dense = dense_numpy(np.asarray(features, dtype=np.float64), level) + oc = np.asarray(out_coords, dtype=np.int64) + out = np.zeros((len(oc), w.shape[0])) + for a in range(k[0]): + for b in range(k[1]): + for c in range(k[2]): + i = oc * s - p + np.array([a, b, c]) * d + inside = np.all((i >= 0) & (i < np.array([X, Y, Z])), axis=1) + if inside.any(): + ii = i[inside] + out[inside] += dense[ii[:, 0], ii[:, 1], ii[:, 2]] @ w[:, a, b, c, :].T + return out + + +def neighbor_stats(nmap: np.ndarray) -> Dict[str, Any]: + """``{rows, pairs, mean_taps, max_taps}`` of a neighbour map (diagnostics, PORT_LOG tables).""" + nm = np.asarray(nmap) + taps = (nm >= 0).sum(axis=1) if len(nm) else np.zeros(0) + return {"rows": int(len(nm)), "pairs": int(taps.sum()), "mean_taps": float(taps.mean()) if len(nm) else 0.0, + "max_taps": int(taps.max()) if len(nm) else 0} + + +def iter_taps(kernel: Any) -> Iterable[Tuple[int, Tuple[int, int, int]]]: + """``(k, (a, b, c))`` in tap order.""" + k = _triple(kernel, "kernel") + for a in range(k[0]): + for b in range(k[1]): + for c in range(k[2]): + yield (a * k[1] + b) * k[2] + c, (a, b, c) diff --git a/code/tt_depthpro2/ttaw/tensors.py b/code/tt_depthpro2/ttaw/tensors.py new file mode 100644 index 0000000000000000000000000000000000000000..d158179af6a09e409f332781598cf6d920b59dbd --- /dev/null +++ b/code/tt_depthpro2/ttaw/tensors.py @@ -0,0 +1,390 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C03: tensor layout and dtype helpers shared by every port. + +Host side (numpy only, no ttnn): tile padding, fixed-capacity padding with a valid count, bf16 bit conversion. +Device side (ttnn imported inside each function): exact host-tensor construction for every dtype (integer arrays are +never routed through a float intermediate), uploads, layout and dtype changes that are no-ops when nothing changes, +fp32 islands (typecast in and out), uint8 uploads with an on-device typecast, readback to numpy, and +:class:`HostStaging`: a persistent host tensor whose buffer is written in place (no ``from_torch`` per frame). + +Measured on this p150b (``logs/ttaw/api_probe_20261007.log``): numpy uint32 arrays round-trip exactly (including +values >= 2**31); uint8 -> bf16 ``ttnn.typecast`` is exact in ROW_MAJOR and TILE layout; ``torch.from_dlpack`` of a +host buffer is a writable alias (``numpy.from_dlpack`` is read-only, ``numpy.asarray`` fails). +""" +from __future__ import annotations + +import math +from typing import Any, Callable, Optional, Sequence, Tuple, Union + +import numpy as np + +__all__ = [ + "TILE", + "round_up", + "tile_padded_shape", + "pad_to_tile", + "pad_to_capacity", + "as_4d", + "float32_to_bf16_bits", + "bf16_bits_to_float32", + "round_to_bf16", + "ttnn_dtype", + "dtype_name", + "to_host_tensor", + "to_device", + "to_numpy", + "host_view", + "to_layout", + "typecast", + "to_fp32", + "to_bf16", + "fp32_island", + "upload_u8", + "HostStaging", +] + +TILE = 32 + +ArrayLike = Union[np.ndarray, Sequence, Any] + + +# ------------------------------------------------------------------------------------------------- host side + +def round_up(n: int, multiple: int = TILE) -> int: + """Smallest multiple of ``multiple`` that is >= ``n``.""" + if multiple <= 0: + raise ValueError("multiple must be positive") + return -(-int(n) // multiple) * multiple + + +def tile_padded_shape(shape: Sequence[int]) -> Tuple[int, ...]: + """``shape`` with its last two dims rounded up to the 32x32 tile (what a TILE tensor occupies).""" + shape = tuple(int(s) for s in shape) + if len(shape) < 2: + raise ValueError(f"need at least 2 dims, got {shape}") + return shape[:-2] + (round_up(shape[-2]), round_up(shape[-1])) + + +def pad_to_tile(array: np.ndarray, value: float = 0.0) -> np.ndarray: + """Pad the last two dims of a host array up to multiples of 32 with ``value`` (copy only when needed).""" + a = np.asarray(array) + target = tile_padded_shape(a.shape) + if target == a.shape: + return a + pad = [(0, 0)] * (a.ndim - 2) + [(0, target[-2] - a.shape[-2]), (0, target[-1] - a.shape[-1])] + return np.pad(a, pad, mode="constant", constant_values=value) + + +def pad_to_capacity(array: np.ndarray, capacity: int, *, axis: int = 0, value: float = 0.0, + truncate: bool = False) -> Tuple[np.ndarray, int]: + """Fixed-capacity buffer for a traced graph: pad ``axis`` to ``capacity`` rows with ``value``. + + Returns ``(padded, n_valid)``. More than ``capacity`` rows raise ``ValueError`` unless ``truncate`` keeps the + first ``capacity`` (the caller must report the overflow). Capacities are grid-independent constants + (PLAN.md section 0.2).""" + a = np.asarray(array) + n = a.shape[axis] + if n > capacity: + if not truncate: + raise ValueError(f"{n} rows exceed the capacity {capacity}") + return np.take(a, np.arange(capacity), axis=axis), capacity + if n == capacity: + return a, n + pad = [(0, 0)] * a.ndim + pad[axis] = (0, capacity - n) + return np.pad(a, pad, mode="constant", constant_values=value), n + + +def as_4d(array: np.ndarray) -> np.ndarray: + """Prepend unit dims up to rank 4 (the ``[N, C, H, W]`` / ``[1, 1, rows, cols]`` convention of ttnn).""" + a = np.asarray(array) + if a.ndim > 4: + raise ValueError(f"rank {a.ndim} > 4") + return a.reshape((1,) * (4 - a.ndim) + a.shape) + + +def float32_to_bf16_bits(array: ArrayLike) -> np.ndarray: + """float32 -> bfloat16 bit patterns (uint16), round-to-nearest-even like ``torch.Tensor.to(torch.bfloat16)``. + NaN stays NaN (quiet bit forced).""" + f = np.ascontiguousarray(array, dtype=np.float32) + bits = f.view(np.uint32).astype(np.uint64) + rounded = (bits + 0x7FFF + ((bits >> 16) & 1)) >> 16 + out = rounded.astype(np.uint16) + nan = np.isnan(f) + if nan.any(): + out[nan] = ((bits[nan] >> 16) | 0x0040).astype(np.uint16) + return out + + +def bf16_bits_to_float32(bits: ArrayLike) -> np.ndarray: + """bfloat16 bit patterns (uint16) -> float32 (exact).""" + b = np.ascontiguousarray(bits, dtype=np.uint16) + return (b.astype(np.uint32) << 16).view(np.float32) + + +def round_to_bf16(array: ArrayLike) -> np.ndarray: + """float32 values rounded to the nearest bfloat16 (RNE), returned as float32: the host emulation of a bf16 + upload, for building exact expectations in tests.""" + return bf16_bits_to_float32(float32_to_bf16_bits(array)) + + +# ----------------------------------------------------------------------------------------------- dtype maps + +_DTYPE_ALIASES = { + "bf16": "bfloat16", "bfloat16": "bfloat16", "fp32": "float32", "float32": "float32", "f32": "float32", + "bfp8": "bfloat8_b", "bfloat8_b": "bfloat8_b", "bf8": "bfloat8_b", "bfp4": "bfloat4_b", "bfloat4_b": "bfloat4_b", + "uint32": "uint32", "u32": "uint32", "int32": "int32", "i32": "int32", "uint16": "uint16", "u16": "uint16", + "uint8": "uint8", "u8": "uint8", +} + +# canonical numpy dtype used to build the host tensor for each ttnn dtype (bf16 / bfp go through float32) +_HOST_NUMPY = {"float32": np.float32, "bfloat16": np.float32, "bfloat8_b": np.float32, "bfloat4_b": np.float32, + "uint32": np.uint32, "int32": np.int32, "uint16": np.uint16, "uint8": np.uint8} + + +def ttnn_dtype(name_or_dtype: Any): + """``"bf16"`` / ``"fp32"`` / ``"bfp8"`` / ``"uint32"`` ... (or a ttnn dtype) -> ``ttnn.DataType``.""" + import ttnn + + if not isinstance(name_or_dtype, str): + return name_or_dtype + key = _DTYPE_ALIASES.get(name_or_dtype.strip().lower()) + if key is None: + raise ValueError(f"unknown dtype {name_or_dtype!r}; expected one of {sorted(_DTYPE_ALIASES)}") + return getattr(ttnn, key) + + +def dtype_name(dtype: Any) -> str: + """Canonical lower-case name of a ttnn dtype (``ttnn.bfloat16`` -> ``"bfloat16"``), or of an alias string.""" + if isinstance(dtype, str): + key = _DTYPE_ALIASES.get(dtype.strip().lower()) + if key is None: + raise ValueError(f"unknown dtype {dtype!r}") + return key + name = getattr(dtype, "name", None) or str(dtype).rsplit(".", 1)[-1] + name = name.lower() + return {"bfloat8_b": "bfloat8_b", "bfloat4_b": "bfloat4_b"}.get(name, name) + + +def _exact_torch(value: ArrayLike, dtype: Any): + """A torch tensor whose dtype matches ``dtype`` exactly for integers (ttnn would otherwise route int64 through + bf16) and is float32 / bf16 for float targets.""" + import torch + + name = dtype_name(dtype) + if isinstance(value, torch.Tensor): + value = value.detach().cpu() + if name == "bfloat16": + return value.to(torch.bfloat16) if value.dtype != torch.bfloat16 else value.contiguous() + if name in ("float32", "bfloat8_b", "bfloat4_b"): + return value.to(torch.float32).contiguous() + value = value.numpy() if value.dtype not in (torch.bfloat16,) else value.float().numpy() + a = np.asarray(value) + target = _HOST_NUMPY[name] + if np.issubdtype(np.dtype(target), np.integer): + if not (np.issubdtype(a.dtype, np.integer) or a.dtype == np.bool_): + raise TypeError(f"{name} tensor needs integer data, got {a.dtype}") + if a.size and np.issubdtype(a.dtype, np.signedinteger) and np.dtype(target).kind == "u" and a.min() < 0: + raise ValueError(f"negative values cannot be stored as {name}") + a = np.ascontiguousarray(a, dtype=target) + if not a.flags.writeable: # broadcast views are read-only; torch.from_numpy wants writable memory + a = a.copy() + t = torch.from_numpy(a) + return t.to(torch.bfloat16) if name == "bfloat16" else t + + +# ------------------------------------------------------------------------------------------- device side + +def to_host_tensor(value: ArrayLike, dtype: Any, layout: Any = None, *, shape: Optional[Sequence[int]] = None): + """numpy / torch / ttnn host tensor -> ttnn host tensor of ``dtype`` and ``layout`` (default ROW_MAJOR). + + A ttnn host tensor is checked (dtype, layout, optional shape) and returned unchanged. TILE layout tilizes on the + host: prefer ROW_MAJOR inputs plus an on-device ``ttnn.to_layout`` for large per-frame tensors.""" + import ttnn + + dtype = ttnn_dtype(dtype) + layout = ttnn.ROW_MAJOR_LAYOUT if layout is None else layout + if isinstance(value, ttnn.Tensor): + if value.storage_type() == ttnn.StorageType.DEVICE: + raise ValueError("expected a host tensor, got a device tensor") + if value.dtype != dtype or value.layout != layout: + raise ValueError(f"host tensor is {value.dtype}/{value.layout}, expected {dtype}/{layout}") + if shape is not None and tuple(value.shape) != tuple(shape): + raise ValueError(f"host tensor has shape {tuple(value.shape)}, expected {tuple(shape)}") + return value + t = _exact_torch(value, dtype) + if shape is not None and tuple(t.shape) != tuple(int(s) for s in shape): + raise ValueError(f"value has shape {tuple(t.shape)}, expected {tuple(shape)}") + return ttnn.from_torch(t, dtype=dtype, layout=layout) + + +def to_device(value: ArrayLike, device, dtype: Any = "bf16", layout: Any = None, memory_config: Any = None): + """Host data -> device tensor (``layout`` default TILE, ``memory_config`` default DRAM interleaved).""" + import ttnn + + layout = ttnn.TILE_LAYOUT if layout is None else layout + host = to_host_tensor(value, dtype, layout) + return ttnn.to_device(host, device, memory_config=memory_config or ttnn.DRAM_MEMORY_CONFIG) + + +def to_numpy(tensor: Any) -> np.ndarray: + """ttnn tensor (device or host) / torch tensor / array -> numpy. bf16 becomes float32 (exact); unsigned torch + dtypes without numpy support are converted through int64.""" + if isinstance(tensor, np.ndarray): + return tensor + try: + import ttnn + except ImportError: + ttnn = None + if ttnn is not None and isinstance(tensor, ttnn.Tensor): + tensor = ttnn.to_torch(tensor) + if hasattr(tensor, "detach") and hasattr(tensor, "cpu"): + import torch + + t = tensor.detach().cpu() + if t.dtype == torch.bfloat16: + return t.float().numpy() + try: + return t.numpy() + except TypeError: # torch.uint16 / uint32 on older numpy bridges + target = {torch.uint16: np.uint16, torch.uint32: np.uint32}.get(t.dtype, np.int64) + return t.to(torch.int64).numpy().astype(target) + return np.asarray(tensor) + + +def host_view(tensor: Any) -> Optional[np.ndarray]: + """Zero-copy numpy view of a ROW_MAJOR ttnn HOST tensor's buffer (single-device shard 0), with the tensor's + logical shape and ``to_numpy``'s dtype; the view keeps the buffer alive. None when the tensor is not ROW_MAJOR, + its dtype has no exact numpy view (bf16 / bfp8 / ...), its buffer is padded, or the runtime has no + ``host_buffer()`` dlpack bridge (callers then use :func:`to_numpy`). ttaw 0.24.2 (METEOR OPT2 round 5).""" + try: + import ttnn + + if tensor.layout != ttnn.ROW_MAJOR_LAYOUT: + return None + npdt = {ttnn.float32: np.float32, ttnn.uint32: np.uint32, ttnn.int32: np.int32, + ttnn.uint16: np.uint16, ttnn.uint8: np.uint8}.get(tensor.dtype) + if npdt is None: + return None + shape = tuple(int(v) for v in tensor.shape) + if tuple(int(v) for v in tensor.padded_shape) != shape: + return None + raw = np.from_dlpack(tensor.host_buffer().get_shard(ttnn.MeshCoordinate(0, 0)).__array__()) + v = raw.reshape(-1).view(npdt) + if v.size != int(np.prod(shape)): + return None + return v.reshape(shape) + except Exception: # noqa: BLE001 - any missing bridge / fake runtime: the copy path + return None + + +def to_layout(tensor, layout): + """``ttnn.to_layout`` that returns the input unchanged when it already has ``layout`` (no extra program).""" + import ttnn + + return tensor if tensor.layout == layout else ttnn.to_layout(tensor, layout) + + +def typecast(tensor, dtype): + """``ttnn.typecast`` that is a no-op when ``tensor`` already has ``dtype``.""" + import ttnn + + dtype = ttnn_dtype(dtype) + return tensor if tensor.dtype == dtype else ttnn.typecast(tensor, dtype) + + +def to_fp32(tensor): + """Enter an fp32 island (typecast to FLOAT32 if needed).""" + return typecast(tensor, "float32") + + +def to_bf16(tensor): + """Leave an fp32 island (typecast to BFLOAT16 if needed).""" + return typecast(tensor, "bfloat16") + + +def fp32_island(fn: Callable[..., Any], *tensors, out_dtype: Any = "bfloat16"): + """Run ``fn`` on fp32 copies of ``tensors`` and cast its tensor output(s) to ``out_dtype`` (``None`` keeps + fp32). For numerically sensitive glue (box coding, softmax logits, geometry) between bf16 stages.""" + out = fn(*(to_fp32(t) for t in tensors)) + if out_dtype is None: + return out + if isinstance(out, (list, tuple)): + return type(out)(typecast(t, out_dtype) for t in out) + return typecast(out, out_dtype) + + +def upload_u8(array: ArrayLike, device, *, out_dtype: Any = "bfloat16", layout: Any = None, memory_config: Any = None): + """Upload uint8 data (4x less PCIe traffic than fp32) and typecast it on the device (exact for 0..255). + + In a traced model keep the uint8 tensor as the persistent trace input and make ``ttnn.typecast`` the first + traced op; this helper is the eager form.""" + import ttnn + + layout = ttnn.ROW_MAJOR_LAYOUT if layout is None else layout + u8 = ttnn.to_device(to_host_tensor(array, "uint8", layout), device, + memory_config=memory_config or ttnn.DRAM_MEMORY_CONFIG) + return typecast(u8, out_dtype) + + +class HostStaging: + """A persistent ROW_MAJOR host tensor written in place for every frame (RP section 2.11, rf-detr R3c). + + ``write(array)`` copies (and casts) into the tensor's own host buffer through a writable ``torch.from_dlpack`` + alias, so no ``ttnn.from_torch`` allocation happens per frame; ``.tensor`` is what you pass to + ``ttnn.copy_host_to_device_tensor`` (or ``TraceRunner.run(inputs=...)``). bf16 is written as RNE-rounded bit + patterns. If the alias check fails on some tt-metal build, ``zero_copy`` is ``False`` and ``write`` rebuilds the + host tensor with ``from_torch`` (same result, slower).""" + + _VIEW = {"float32": np.float32, "bfloat16": np.uint16, "uint32": np.uint32, "int32": np.int32, + "uint16": np.uint16, "uint8": np.uint8} + + def __init__(self, shape: Sequence[int], dtype: Any = "float32"): + import torch + import ttnn + + self.shape = tuple(int(s) for s in shape) + self.dtype = ttnn_dtype(dtype) + self._name = dtype_name(self.dtype) + if self._name not in self._VIEW: + raise ValueError(f"HostStaging supports {sorted(self._VIEW)}, not {self._name}") + zeros = np.zeros(self.shape, _HOST_NUMPY[self._name]) + self.tensor = ttnn.from_torch(_exact_torch(zeros, self.dtype), dtype=self.dtype, layout=ttnn.ROW_MAJOR_LAYOUT) + self.zero_copy = False + self._keep: tuple = () + try: + shard = self.tensor.host_buffer().get_shard(ttnn.MeshCoordinate(0, 0)) + raw = torch.from_dlpack(shard) + view = raw.numpy().view(self._VIEW[self._name]).reshape(self.shape) + probe = (np.arange(view.size) % 251 + 1).astype(view.dtype).reshape(self.shape) + view[...] = probe + back = to_numpy(self.tensor) + expect = bf16_bits_to_float32(probe) if self._name == "bfloat16" else probe + if np.array_equal(back.reshape(self.shape), expect): + self.zero_copy = True + self._keep = (shard, raw) + self.view = view + view[...] = 0 + except Exception: # noqa: BLE001 -- API drift: fall back to from_torch per write + self.zero_copy = False + if not self.zero_copy: + self.view = np.zeros(self.shape, self._VIEW[self._name]) + + def write(self, array: ArrayLike): + """Copy ``array`` (broadcastable to ``shape``) into the host buffer and return the host tensor.""" + a = np.asarray(array) + if self._name == "bfloat16": + self.view[...] = float32_to_bf16_bits(np.broadcast_to(a, self.shape)) + else: + self.view[...] = np.broadcast_to(a, self.shape).astype(self.view.dtype, copy=False) + if not self.zero_copy: + import ttnn + + data = bf16_bits_to_float32(self.view) if self._name == "bfloat16" else self.view + self.tensor = ttnn.from_torch(_exact_torch(data, self.dtype), dtype=self.dtype, + layout=ttnn.ROW_MAJOR_LAYOUT) + return self.tensor + + @property + def nbytes(self) -> int: + return int(math.prod(self.shape) * self.view.dtype.itemsize) diff --git a/code/tt_depthpro2/ttaw/trace.py b/code/tt_depthpro2/ttaw/trace.py new file mode 100644 index 0000000000000000000000000000000000000000..fe9a85266435334e967e872320ecc8fc23fa062d --- /dev/null +++ b/code/tt_depthpro2/ttaw/trace.py @@ -0,0 +1,1350 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C02: ``TraceRunner`` -- every device stage of a port runs inside metal traces. + +What it enforces (TT_PLATFORM.md section 3, REFERENCE_PATTERNS.md section 1.4): + +1. **Persistent I/O before any capture.** Inputs, RT-dev parameters, state buffers and (optionally) output buffers + are allocated (and given defined initial values: never uninitialised index buffers) when they are added, i.e. + before the first capture. A variant returns either the tensors its last ops produce (allocated during capture, + valid while the trace lives) or persistent outputs written with ``ctx.write_output`` (stable addresses shared by + several variants, never overwritten by another variant's replay). +2. **Warm-up, then capture.** Every variant runs eagerly ``warmup_runs`` times (kernel JIT, program cache, prepared + conv weights) before *any* trace is captured. Adding a variant after a capture releases all traces, warms the new + one and recaptures everything, because a warm-up after a capture could allocate into a trace's freed + intermediates. +3. **Strict capture.** ``device.set_program_cache_misses_allowed(False)`` during capture (a miss raises with the op + name instead of aborting with "Writes are not supported during trace capture"); ``end_trace_capture`` runs in a + ``finally`` block and a failed capture is released (an open capture left the process spinning in close_device: + RP section 1.4); the program-cache entry count must not change during capture. +4. **Variants.** Several traces keyed by name (shape buckets, modes, segments), chosen by the caller per run. +5. **RT-dev parameters.** Per-frame values that must not change the program (thresholds, timesteps, poses) live + in persistent device tensors refreshed before ``execute_trace``; unchanged values are not re-uploaded. +6. **1CQ / 2CQ.** With 2 CQs inputs are uploaded on CQ1 and ordered with events, exactly like + ``common/tools/check_dispatch.py`` (CQ1 waits for the last trace, uploads, records; CQ0 waits, replays, records). + ``stage_inputs=True`` uses the ``tt_cnn`` executor pattern instead: CQ1 writes a DRAM staging copy while the + previous trace still runs, and an eager copy on CQ0 moves it into the trace input before the replay. Every CQ0 + write into a trace input outside the protocol (:meth:`TraceRunner.write_input`) re-records the event CQ1 waits for. +7. **State inside the trace.** ``ctx.write_state(name, value)`` is ``ttnn.copy(value, buffer)`` into a persistent + buffer (FLOAT32 / UINT32 / BFLOAT16 / ... all supported), or no op at all when ``value`` was computed straight + into ``ctx.write_target(name)`` (``output_tensor=``). ``pingpong=True`` states use two buffers and two traces + per variant (phase 0 reads A writes B, phase 1 reads B writes A); the phase flips after every run of a variant + that writes the ping-pong states. Per-stream state (PLAN.md D16): ``add_state(..., banks=n)`` + + :meth:`TraceRunner.save_state` / :meth:`TraceRunner.load_state`, with the policy in :class:`StreamBanks`. +8. **Readback.** One packed output (:func:`pack_outputs`) gives one D2H; reads go into preallocated host tensors, + on CQ0 or (segmented pipelines, 2CQ) on CQ1 after a host-side event wait. +9. **Alloc tracking.** With ``TT_METAL_TRACE_ALLOC_TRACKING=1`` set before ``import ttnn``, ``ttnn.execute_trace`` + refuses to replay over live unsafe buffers; the runner acknowledges the outputs of traces captured after the + first one (they may be overwritten by an earlier trace's replay: read outputs before running another variant). + +Example:: + + runner = TraceRunner(device, num_command_queues=2) + runner.add_input("x", shape=(1, 1, 64, 64), dtype="bfloat16", layout=ttnn.TILE_LAYOUT) + runner.add_param("scale", 1.0) # fp32 [1,1,1,1], TILE + runner.add_variant("default", lambda ctx: ttnn.relu(ttnn.multiply(ctx["x"], ctx["scale"]))) + runner.capture() # warm-up, then capture + y = runner("default", inputs={"x": x_np}, params={"scale": 0.5}) # upload, replay, read -> numpy +""" +from __future__ import annotations + +import contextlib +import math +import time +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Tuple + +import numpy as np + +from .io import InputError +from .tensors import TILE, dtype_name, host_view, round_up, to_host_tensor, to_numpy, ttnn_dtype + +__all__ = [ + "CQ_COMPUTE", + "CQ_INPUT", + "PackEntry", + "PackLayout", + "Packed", + "pack_outputs", + "SINGLE_ROW_MAX_ELEMS", + "PACK_ROW_ELEMS", + "TraceContext", + "TraceRunner", + "StreamBanks", + "alloc_tracking_enabled", +] + +CQ_COMPUTE = 0 # programs, traces and (by default) readback +CQ_INPUT = 1 # host -> device uploads when the device has 2 command queues + + +def alloc_tracking_enabled() -> bool: + """True when ``TT_METAL_TRACE_ALLOC_TRACKING=1`` was set before ttnn was imported (read from tt-metal).""" + try: + from ttnn.tools import trace_allocation_tracker as tracker + except ImportError: + return False + return bool(getattr(tracker, "TRACE_ALLOC_TRACKING", False)) + + +# ----------------------------------------------------------------------------------------------- packing + +# Packed layouts (PORT_LOG Q9 of the YOLOX port). A ROW_MAJOR tensor is stored page by page, one page per row, and +# the RM reshape / concat programs stage whole pages in L1 (reshape_rm_program_factory.cpp: 2 x the destination page +# per kernel copy when the pages are not 16-byte aligned), so a single-row pack of more than ~0.6 MB fails with +# "RM reshape dest staging does not fit in L1". Above SINGLE_ROW_MAX_ELEMS the pack is a [1, 1, rows, R] tensor of +# R = PACK_ROW_ELEMS elements per row: every RM page the packing programs touch stays below ROW_PAGE_MAX_BYTES, +# whatever the size of the outputs (tens of MB), and the readback is still ONE device-to-host copy. +SINGLE_ROW_MAX_ELEMS = 131072 # one [1, 1, 1, total] row up to 512 KiB of float32 (the 0.1.0 - 0.14.0 layout) +PACK_ROW_ELEMS = 1024 # elements per row of the multi-row layout (4 KiB float32 pages) +FLAT_MAX_BYTES = 64 << 10 # multi-row: tensors up to this size are flattened to one row, then cut into rows +ROW_PAGE_MAX_BYTES = 128 << 10 # multi-row: largest RM page (last dim x element size) a packed tensor may have +_ELEM_BYTES = {"float32": 4, "uint32": 4, "int32": 4, "bfloat16": 2, "uint16": 2, "uint8": 1} + + +@dataclass(frozen=True) +class PackEntry: + """One tensor inside a packed readback: elements ``[offset, offset + numel)`` reshaped to ``shape``. + + ``pitch > 0`` (multi-row layout only): the tensor's rows (its last dim, ``shape[-1]`` elements) + are stored ``pitch`` elements apart, zero-padded, i.e. elements ``[offset, offset + numel // shape[-1] * pitch)`` + viewed as ``(rows, pitch)`` hold it in their first ``shape[-1]`` columns. ``0``: contiguous.""" + + name: str + offset: int + numel: int + shape: Tuple[int, ...] + pitch: int = 0 + + def view(self, flat: np.ndarray) -> np.ndarray: + """This tensor inside the flat readback ``flat`` (a view, strided when ``pitch`` is set).""" + if not self.pitch: + return flat[self.offset:self.offset + self.numel].reshape(self.shape) + cols = int(self.shape[-1]) if self.shape else 1 + rows = self.numel // cols + return flat[self.offset:self.offset + rows * self.pitch].reshape(rows, self.pitch)[:, :cols].reshape( + self.shape) + + +@dataclass(frozen=True) +class PackLayout: + """Host-side description of a packed output (built at capture time, applied at every read). + + ``entries`` index the packed tensor's elements in row-major order, so :meth:`unpack` does not depend on the + device shape ``(1, 1, rows, row_elems)``: one row of ``total`` elements (``rows == 1``) or rows of + ``row_elems`` elements, every tensor starting on a row boundary (multi-row layout; an entry with a ``pitch`` + stores its rows zero-padded to that many elements, see :class:`PackEntry`).""" + + entries: Tuple[PackEntry, ...] + total: int + rows: int = 1 + row_elems: int = 0 # 0: one row of ``total`` elements + + @property + def shape(self) -> Tuple[int, int, int, int]: + """Shape of the packed device tensor.""" + return (1, 1, self.rows, self.row_elems or self.total) + + def unpack(self, flat: Any) -> Dict[str, np.ndarray]: + """Flat readback (any shape with ``total`` elements) -> ``{name: array}`` (views, no copies; the view of an + entry with a ``pitch`` is strided, not C-contiguous).""" + a = np.asarray(flat).reshape(-1) + if a.size != self.total: + raise ValueError(f"packed readback has {a.size} elements, layout expects {self.total}") + return {e.name: e.view(a) for e in self.entries} + + +@dataclass +class Packed: + """A packed device tensor plus its layout; return it from a variant function to get ``{name: array}`` back.""" + + tensor: Any + layout: PackLayout + + +def _elem_bytes(dtype: Any) -> int: + return _ELEM_BYTES.get(dtype_name(dtype), 4) + + +def _row_major(ttnn: Any, t: Any, dtype: Any) -> Any: + if t.dtype != dtype: + t = ttnn.typecast(t, dtype) + if t.layout != ttnn.ROW_MAJOR_LAYOUT: + t = ttnn.to_layout(t, ttnn.ROW_MAJOR_LAYOUT) + return t + + +def _flat_rows(ttnn: Any, t: Any, shape: Tuple[int, ...], numel: int, row_elems: int) -> Tuple[Any, int]: + """A small RM tensor -> one row -> zero-padded to whole rows -> ``[1, 1, k, row_elems]``.""" + padded = round_up(numel, row_elems) + if shape != (1, 1, 1, numel): + t = ttnn.reshape(t, (1, 1, 1, numel)) + if padded != numel: + t = ttnn.pad(t, [(0, 0), (0, 0), (0, 0), (0, padded - numel)], 0.0) + if padded != row_elems: + t = ttnn.reshape(t, (1, 1, padded // row_elems, row_elems)) + return t, padded + + +def _fill_rows(rows: int, cols: int, row_elems: int) -> int: + """Rows of ``cols`` elements a ``[rows, cols]`` tensor is zero-padded to so that it fills whole packed rows.""" + return round_up(rows, row_elems // math.gcd(cols, row_elems)) + + +def _row_pitches(cols: int, row_elems: int, elem: int) -> List[int]: + """Row pitches > ``cols`` worth trying: ``cols`` rounded up to every power of two dividing ``row_elems`` (rows of + that pitch fill a packed row every ``row_elems / gcd`` rows) and to ``row_elems`` (every row fills whole packed + rows), within the page budget.""" + steps, m = {row_elems}, 2 + while row_elems % m == 0: + steps.add(m) + m *= 2 + return sorted({p for p in (round_up(cols, m) for m in steps) if p != cols and p * elem <= ROW_PAGE_MAX_BYTES}) + + +def _pack_rows_segment(ttnn: Any, name: str, t: Any, shape: Tuple[int, ...], numel: int, row_elems: int, + elem: int) -> Tuple[Any, int, int]: + """One ROW_MAJOR tensor -> ``[1, 1, k, row_elems]`` holding its elements in order, zero-padded to whole rows. + Returns ``(segment, k * row_elems, pitch)`` (``pitch``: see :class:`PackEntry`). No RM page above + ``ROW_PAGE_MAX_BYTES`` is created or reshaped.""" + cols = int(shape[-1]) if shape else 1 + rows = numel // cols + if cols * elem <= ROW_PAGE_MAX_BYTES: + # [rows, cols] is a view of the RM tensor; rows * cols fills whole packed rows when rows % unit == 0 + rows_p = _fill_rows(rows, cols, row_elems) + if rows_p != rows and numel * elem <= FLAT_MAX_BYTES: + return (*_flat_rows(ttnn, t, shape, numel, row_elems), 0) # small: pad < row_elems elements, not rows + if rows_p != rows: + # Appending zero rows costs up to row_elems / gcd(cols, row_elems) - 1 rows: 80 MB for a [1, 1, 2, 20001] + # fp32 tensor. Take one flat row (when it fits the page budget) or rows zero-padded to a pitch instead + # when that is smaller by more than 1/8 of the tensor (typical shapes keep the contiguous layout). + options = [(p * _fill_rows(rows, p, row_elems), p) for p in _row_pitches(cols, row_elems, elem)] + if round_up(numel, row_elems) * elem <= ROW_PAGE_MAX_BYTES: + options.append((round_up(numel, row_elems), 0)) + if options and rows_p * cols - min(options)[0] > numel // 8: + size, pitch = min(options) # ties: the flat row, then the narrower pitch + if not pitch: + return (*_flat_rows(ttnn, t, shape, numel, row_elems), 0) + prows = size // pitch + if shape != (1, 1, rows, cols): + t = ttnn.reshape(t, (1, 1, rows, cols)) + t = ttnn.pad(t, [(0, 0), (0, 0), (0, prows - rows), (0, pitch - cols)], 0.0) + if pitch != row_elems: + t = ttnn.reshape(t, (1, 1, size // row_elems, row_elems)) + return t, size, pitch + # zero rows appended, then one RM reshape into rows of row_elems (source pages of cols elements, destination + # pages of row_elems elements: both small) + if shape != (1, 1, rows, cols): + t = ttnn.reshape(t, (1, 1, rows, cols)) + if rows_p != rows: + t = ttnn.pad(t, [(0, 0), (0, 0), (0, rows_p - rows), (0, 0)], 0.0) + if cols != row_elems: + t = ttnn.reshape(t, (1, 1, rows_p * cols // row_elems, row_elems)) + return t, rows_p * cols, 0 + if rows != 1: + raise ValueError(f"pack_outputs: {name!r} {shape} has rows of {cols * elem} B; the multi-row layout reads " + f"RM rows of at most {ROW_PAGE_MAX_BYTES} B: give it a narrower last dim (e.g. " + f"[1, 1, -1, {row_elems}]) before packing") + # one wide row (a flat vector): cut it into chunks of whole packed rows, each well inside the L1 budget + if shape != (1, 1, 1, numel): + t = ttnn.reshape(t, (1, 1, 1, numel)) + width = max(row_elems, (ROW_PAGE_MAX_BYTES // elem) // row_elems * row_elems) + parts, total = [], 0 + for start in range(0, numel, width): + stop = min(start + width, numel) + chunk = ttnn.slice(t, [0, 0, 0, start], [1, 1, 1, stop]) + chunk, padded = _flat_rows(ttnn, chunk, (1, 1, 1, stop - start), stop - start, row_elems) + parts.append(chunk) + total += padded + return (parts[0] if len(parts) == 1 else ttnn.concat(parts, dim=2)), total, 0 + + +def pack_outputs(tensors: Mapping[str, Any], *, dtype: Any = "float32", align: int = 32, + row_elems: Optional[int] = None) -> Packed: + """Pack several device tensors into ONE ROW_MAJOR tensor so the host reads them with one device-to-host copy. + + Each tensor is typecast to ``dtype`` (float32 default: exact for bf16 and for integers below 2**24) and converted + to ROW_MAJOR; call this inside the variant function (the ops become part of the trace) and return the result. + :meth:`PackLayout.unpack` (done by ``TraceRunner.read``) gives ``{name: array}`` back in the original shapes. + + Device layout: while the packed total is at most :data:`SINGLE_ROW_MAX_ELEMS`, one ``[1, 1, 1, total]`` row (each + tensor flattened and zero-padded to ``align`` elements, then concatenated): a ``[1, 1, N, 1]`` RM readback is N + pages and costs milliseconds, one row is one page (RP section 1.4). Above it (or with ``row_elems=R``) a + ``[1, 1, rows, R]`` tensor (default R = :data:`PACK_ROW_ELEMS`): each tensor is zero-padded to whole rows of R + elements and the segments are concatenated on the row dim, so no RM page exceeds :data:`ROW_PAGE_MAX_BYTES` + and outputs of tens of MB pack (a single row of more than ~0.6 MB does not fit the RM reshape's L1 staging: + YOLOX PORT_LOG Q9). A tensor is padded with zero rows (contiguous), or, when that wastes more than 1/8 of it + (an awkward last dim with few rows: e.g. ``[1, 1, 2, 20001]`` would take 1024 rows), flattened (up to the page + budget) or stored with its rows zero-padded to a wider pitch (:class:`PackEntry` ``pitch``). A last dim wider + than ``ROW_PAGE_MAX_BYTES`` is accepted for a flat vector (``[1, 1, 1, N]``, cut into chunks with + ``ttnn.slice``); any other tensor needs a narrower last dim (``ValueError``).""" + import ttnn + + if not tensors: + raise ValueError("pack_outputs needs at least one tensor") + if align <= 0: + raise ValueError("align must be positive") + if row_elems is not None and (int(row_elems) <= 0 or int(row_elems) % TILE): + raise ValueError(f"row_elems={row_elems}: expected a positive multiple of {TILE}") + dtype = ttnn_dtype(dtype) + elem = _elem_bytes(dtype) + items = [(str(name), t, tuple(int(s) for s in t.shape)) for name, t in tensors.items()] + empty = [name for name, _, shape in items if math.prod(shape) == 0] + if empty: + raise ValueError(f"pack_outputs: {empty} have no elements") + single_total = sum(round_up(math.prod(shape), align) for _, _, shape in items) + if row_elems is None and single_total <= SINGLE_ROW_MAX_ELEMS: + segments, entries, offset = [], [], 0 + for name, t, shape in items: # the single-row layout of ttaw 0.1.0 - 0.14.0 + numel = math.prod(shape) + t = _row_major(ttnn, t, dtype) + if shape != (1, 1, 1, numel): + t = ttnn.reshape(t, (1, 1, 1, numel)) + padded = round_up(numel, align) + if padded != numel: + t = ttnn.pad(t, [(0, 0), (0, 0), (0, 0), (0, padded - numel)], 0.0) + segments.append(t) + entries.append(PackEntry(name, offset, numel, shape)) + offset += padded + packed = segments[0] if len(segments) == 1 else ttnn.concat(segments, dim=-1) + return Packed(packed, PackLayout(tuple(entries), offset)) + r = int(row_elems or PACK_ROW_ELEMS) + segments, entries, offset = [], [], 0 + for name, t, shape in items: + numel = math.prod(shape) + t, padded, pitch = _pack_rows_segment(ttnn, name, _row_major(ttnn, t, dtype), shape, numel, r, elem) + segments.append(t) + entries.append(PackEntry(name, offset, numel, shape, pitch)) + offset += padded + packed = segments[0] if len(segments) == 1 else ttnn.concat(segments, dim=2) + return Packed(packed, PackLayout(tuple(entries), offset, rows=offset // r, row_elems=r)) + + +# --------------------------------------------------------------------------------------------- internals + +@dataclass +class _Slot: + """A persistent device tensor (input, parameter or state) allocated before any capture.""" + + name: str + kind: str # "input" | "param" | "state" | "output" + shape: Tuple[int, ...] + dtype: Any + layout: Any + memory_config: Any + buffers: List[Any] # 1 buffer, or 2 for a ping-pong state + init: Any # host tensor holding the initial value (states, params) / warm-up value (inputs) + staging: Any = None # DRAM staging copy (2CQ stage_inputs mode) + stage_fn: Optional[Callable[[Any, Any], Any]] = None + last_value: Optional[bytes] = None # params: bytes of the last uploaded value (skip unchanged uploads) + banks: List[Any] = field(default_factory=list) # states: save / load buffers (D16 per-stream state banks) + + @property + def pingpong(self) -> bool: + return len(self.buffers) == 2 + + def tensors(self) -> List[Any]: + """Every device tensor the slot owns.""" + return self.buffers + ([self.staging] if self.staging is not None else []) + self.banks + + +@dataclass +class _Variant: + name: str + fn: Callable[["TraceContext"], Any] + warmup_runs: int + + +@dataclass +class _Trace: + variant: str + phase: int + trace_id: Any + outputs: Any + leaves: List[Tuple[Tuple, Any, Optional[PackLayout]]] # (path, device tensor, pack layout or None) + steps: bool # writes the ping-pong states (flips the phase) + capture_ms: float + host_buffers: Optional[List[Any]] = None + done_event: Any = None + + +def _flatten(obj: Any, path: Tuple = ()) -> Iterator[Tuple[Tuple, Any]]: + """Leaves of a tensor / Packed / list / tuple / dict structure with their paths.""" + if isinstance(obj, Mapping): + for k, v in obj.items(): + yield from _flatten(v, path + (k,)) + elif isinstance(obj, (list, tuple)): + for i, v in enumerate(obj): + yield from _flatten(v, path + (i,)) + else: + yield path, obj + + +def _rebuild(obj: Any, values: Dict[Tuple, Any], path: Tuple = ()) -> Any: + if isinstance(obj, Mapping): + return {k: _rebuild(v, values, path + (k,)) for k, v in obj.items()} + if isinstance(obj, (list, tuple)): + return type(obj)(_rebuild(v, values, path + (i,)) for i, v in enumerate(obj)) + return values[path] + + +def _buffer_address(t: Any) -> Optional[int]: + try: + return int(t.buffer_address()) + except Exception: # noqa: BLE001 -- host tensor, deallocated tensor or a fake + return None + + +def _same_buffer(a: Any, b: Any) -> bool: + """``a`` is ``b`` or a tensor over the same device buffer.""" + if a is b: + return True + addr = _buffer_address(a) + return addr is not None and addr == _buffer_address(b) + + +def _check_copy(what: str, value: Any, slot: "_Slot") -> None: + """The preconditions of ``ttnn.copy(value, )``, checked in Python so a mistake is a clear error + instead of a TT_FATAL inside an open capture: same logical shape and layout; a dtype change only in TILE.""" + import ttnn + + shape = tuple(int(s) for s in value.shape) + if shape != slot.shape: + raise ValueError(f"{what}: value shape {shape} != {slot.shape}") + if value.layout != slot.layout: + raise ValueError(f"{what}: value layout {value.layout} != {slot.layout} (ttnn.copy keeps the layout)") + if value.dtype != slot.dtype and slot.layout != ttnn.TILE_LAYOUT: + raise ValueError(f"{what}: dtype {value.dtype} -> {slot.dtype} needs TILE layout (ttnn.copy)") + + +class TraceContext(Mapping): + """What a variant function receives: persistent tensors by name (``ctx["x"]``), and state writes. + + ``ctx[name]`` returns an input, a parameter, a persistent output buffer, or the buffer a state is *read* from in + this phase. ``ctx.write_state(name, value)`` copies ``value`` into the buffer the state is *written* to (in-place + states: the same buffer, so read everything you need from it before writing); ``ctx.write_output(name, value)`` + copies into a persistent output and returns it.""" + + def __init__(self, runner: "TraceRunner", variant: str, phase: int, capturing: bool): + self._runner = runner + self.variant = variant + self.phase = phase + self.capturing = capturing + self.writes: set = set() + + @property + def device(self): + return self._runner.device + + def __getitem__(self, name: str): + slot = self._runner._slot(name) + if slot.kind == "state": + return self.state(name) + return slot.buffers[0] + + def __iter__(self) -> Iterator[str]: + return iter(self._runner._slots) + + def __len__(self) -> int: + return len(self._runner._slots) + + def state(self, name: str): + """The buffer state ``name`` is read from in this phase.""" + slot = self._runner._slot(name, "state") + return slot.buffers[self.phase] if slot.pingpong else slot.buffers[0] + + def write_target(self, name: str): + """The buffer state ``name`` is written to in this phase (ping-pong: the other buffer; in place: the same + one). Pass it as ``output_tensor=`` of the op that produces the new state and then call + ``write_state(name, it)``: no copy program is traced (probe P13: saves one program per state per frame).""" + slot = self._runner._slot(name, "state") + return slot.buffers[1 - self.phase] if slot.pingpong else slot.buffers[0] + + def write_state(self, name: str, value) -> None: + """``ttnn.copy(value, )``: same logical shape and layout as the state (dtype may differ in + TILE layout). The copy is part of the trace; it is skipped when ``value`` already is the write buffer + (:meth:`write_target`).""" + import ttnn + + slot = self._runner._slot(name, "state") + target = self.write_target(name) + _check_copy(f"state {name!r}", value, slot) + if not _same_buffer(value, target): + ttnn.copy(value, target) + self.writes.add(name) + + def write_output(self, name: str, value): + """``ttnn.copy(value, )`` (part of the trace); returns the output buffer, which the + variant can return as (part of) its outputs. Skipped when ``value`` already is that buffer.""" + import ttnn + + slot = self._runner._slot(name, "output") + _check_copy(f"output {name!r}", value, slot) + if not _same_buffer(value, slot.buffers[0]): + ttnn.copy(value, slot.buffers[0]) + return slot.buffers[0] + + +class TraceRunner: + """Persistent device I/O + warm-up + capture + replay of one model's traced stages (see the module docstring). + + Args: + device: an open ttnn device. + num_command_queues: 1 or 2. ``None`` uses what :func:`.device.open_device` recorded (1 if unknown). + warmup_runs: eager runs of each variant (and phase) before any capture. + stage_inputs: 2CQ only: upload into DRAM staging buffers and copy them into the trace inputs with an eager + op on CQ0 (the upload of frame k+1 then overlaps the replay of frame k). + forbid_cache_misses: call ``device.set_program_cache_misses_allowed(False)`` during capture. + alloc_tracking: ``True`` raises unless the process tracks trace allocations + (``TT_METAL_TRACE_ALLOC_TRACKING=1`` set before ``import ttnn``). Whenever tracking is active, the outputs + of traces captured after the first are acknowledged as corruptible (see the module docstring). + name: label used in messages and ``describe()``. + read_view: (ttaw 0.24.2) :meth:`read` copies each ROW_MAJOR output with an exact numpy dtype into a FRESH host + tensor per read and returns a zero-copy view of its buffer (:func:`tensors.host_view`), instead of + copying into the preallocated host tensor and converting it with ``to_numpy`` (a second host copy). + The arrays are fresh per read either way (callers may keep them). Default False (unchanged); outputs + without a view (TILE, bf16, ...) take the copy path. + """ + + def __init__(self, device, *, num_command_queues: Optional[int] = None, warmup_runs: int = 1, + stage_inputs: bool = False, forbid_cache_misses: bool = True, alloc_tracking: Optional[bool] = None, + name: str = "model", read_view: bool = False): + from .device import open_info + + opened = open_info(device).get("num_command_queues") + if num_command_queues is None: + num_command_queues = opened or 1 + if num_command_queues not in (1, 2): + raise ValueError(f"num_command_queues={num_command_queues}: expected 1 or 2") + if opened is not None and num_command_queues > opened: + raise ValueError(f"the device was opened with {opened} command queue(s); cannot run {num_command_queues}") + if stage_inputs and num_command_queues != 2: + raise ValueError("stage_inputs=True needs num_command_queues=2") + if warmup_runs < 1: + raise ValueError("warmup_runs must be >= 1 (capture needs a warm program cache)") + tracking = alloc_tracking_enabled() + if alloc_tracking and not tracking: + raise RuntimeError("alloc_tracking=True but trace allocation tracking is off: export " + "TT_METAL_TRACE_ALLOC_TRACKING=1 (optionally TT_METAL_TRACE_ALLOC_TRACEBACKS=1) " + "before Python imports ttnn") + self.device = device + self.name = name + self.num_command_queues = int(num_command_queues) + self.warmup_runs = int(warmup_runs) + self.stage_inputs = bool(stage_inputs) + self.forbid_cache_misses = bool(forbid_cache_misses) + self.read_view = bool(read_view) + self.alloc_tracking = bool(tracking) + self._slots: Dict[str, _Slot] = {} + self._variants: Dict[str, _Variant] = {} + self._traces: Dict[Tuple[str, int], _Trace] = {} + self._phase = 0 + self._last_phase: Dict[str, int] = {} + self._runs = 0 # 0.24.3: replays so far (a partial read's rest is valid until the next) + self._last_variant: Optional[str] = None + self._pending_params: Dict[str, Any] = {} + self._op_event = None + self._stage_free_event = None + self._captures = 0 + self._capturing = False + self._eager_warmups: List[Callable[[], Any]] = [] + self._eager_warmed = False + self._closed = False + self.timings_ms: Dict[str, Dict[str, float]] = {} + if hasattr(device, "enable_program_cache"): + device.enable_program_cache() + + # ------------------------------------------------------------------------------------- registration + def _check_registration(self, what: str) -> None: + self._check_open() + if self._capturing: + raise RuntimeError(f"cannot add {what} while a variant is being warmed up or captured: register " + "inputs, params, states, outputs and variants before capture()") + + def _new_slot(self, name: str, kind: str, init: Any, shape: Optional[Sequence[int]], dtype: Any, layout: Any, + memory_config: Any, n_buffers: int, stage_fn: Optional[Callable], n_banks: int = 0) -> _Slot: + import ttnn + + self._check_registration(f"{kind} {name!r}") + if name in self._slots: + raise ValueError(f"{name!r} is already registered (as {self._slots[name].kind})") + if self._traces: + raise RuntimeError(f"cannot add {kind} {name!r} after capture: persistent tensors must exist before the " + "first capture (release() and rebuild)") + layout = ttnn.ROW_MAJOR_LAYOUT if layout is None else layout + memory_config = ttnn.DRAM_MEMORY_CONFIG if memory_config is None else memory_config + dtype = ttnn_dtype(dtype) + if init is None: + if shape is None: + raise ValueError(f"{kind} {name!r}: give init= or shape=") + init = np.zeros(tuple(shape), np.float32 if dtype_name(dtype) in ("float32", "bfloat16", "bfloat8_b", + "bfloat4_b") else np.int64) + if isinstance(init, ttnn.Tensor): + host = to_host_tensor(init, dtype, layout, shape=shape) + else: + arr = to_numpy(init) if hasattr(init, "detach") else np.asarray(init) + if shape is not None: + arr = np.broadcast_to(arr, tuple(shape)) + host = to_host_tensor(arr, dtype, layout) + shape_t = tuple(int(s) for s in host.shape) + + def allocate(config: Any): + buf = ttnn.allocate_tensor_on_device(ttnn.Shape(list(shape_t)), dtype, layout, self.device, config) + ttnn.copy_host_to_device_tensor(host, buf, cq_id=CQ_COMPUTE) # defined contents, never garbage + return buf + + buffers = [allocate(memory_config) for _ in range(n_buffers)] + staging = allocate(ttnn.DRAM_MEMORY_CONFIG) if self.stage_inputs and kind in ("input", "param") else None + banks = [allocate(ttnn.DRAM_MEMORY_CONFIG) for _ in range(n_banks)] + slot = _Slot(name, kind, shape_t, dtype, layout, memory_config, buffers, host, staging, + stage_fn or (lambda src, dst: ttnn.copy(src, dst)), banks=banks) + self._slots[name] = slot + return slot + + def add_input(self, name: str, init: Any = None, *, shape: Optional[Sequence[int]] = None, + dtype: Any = "bfloat16", layout: Any = None, memory_config: Any = None, + stage_fn: Optional[Callable[[Any, Any], Any]] = None): + """A persistent trace input (default ROW_MAJOR in DRAM). ``init`` (array / torch / ttnn host tensor) is the + initial content and the warm-up input; zeros of ``shape`` otherwise -- give real data when the graph + gathers with these values (garbage indices can hang the chip). ``stage_fn(staging, persistent)`` replaces + the eager ``ttnn.copy`` in ``stage_inputs`` mode (e.g. a reshard into a sharded L1 input). Returns the + device tensor.""" + return self._new_slot(name, "input", init, shape, dtype, layout, memory_config, 1, stage_fn).buffers[0] + + def add_param(self, name: str, value: Any = 0.0, *, shape: Sequence[int] = (1, 1, 1, 1), dtype: Any = "float32", + layout: Any = None, memory_config: Any = None): + """An RT-dev parameter: a persistent device tensor (default fp32 ``[1, 1, 1, 1]`` TILE, which broadcasts in + ttnn binary ops) refreshed before a replay when ``run(params=...)`` / :meth:`set_params` changes it.""" + import ttnn + + layout = ttnn.TILE_LAYOUT if layout is None else layout + slot = self._new_slot(name, "param", np.broadcast_to(np.asarray(value), tuple(shape)), tuple(shape), dtype, + layout, memory_config, 1, None) + slot.last_value = self._param_bytes(slot, value) + return slot.buffers[0] + + def add_state(self, name: str, init: Any = None, *, shape: Optional[Sequence[int]] = None, dtype: Any = "float32", + layout: Any = None, memory_config: Any = None, pingpong: bool = False, banks: int = 0): + """Temporal state kept on the device across replays (memory queues, previous BEV, ring buffers). + + In-place (default): one buffer, read via ``ctx[name]`` and written via ``ctx.write_state``. ``pingpong``: + two buffers and two traces per variant. ``init`` is restored by :meth:`reset_state`. ``banks``: extra DRAM + buffers of the same spec for :meth:`save_state` / :meth:`load_state` (one per stream id of a + :class:`StreamBanks`, PLAN.md D16), allocated now because nothing may be allocated after a capture. + Returns the buffer(s).""" + import ttnn + + if banks < 0: + raise ValueError("banks must be >= 0") + layout = ttnn.TILE_LAYOUT if layout is None else layout + slot = self._new_slot(name, "state", init, shape, dtype, layout, memory_config, 2 if pingpong else 1, None, + n_banks=int(banks)) + return tuple(slot.buffers) if pingpong else slot.buffers[0] + + def add_output(self, name: str, *, shape: Sequence[int], dtype: Any = "float32", layout: Any = None, + memory_config: Any = None): + """A persistent output buffer (default TILE in DRAM, zeros) allocated before any capture. Variants write it + with ``ctx.write_output(name, value)`` (one traced ``ttnn.copy``) and return it; its address survives + recaptures and is shared by every variant (e.g. shape buckets with one readback). Returns the buffer.""" + import ttnn + + layout = ttnn.TILE_LAYOUT if layout is None else layout + return self._new_slot(name, "output", None, shape, dtype, layout, memory_config, 1, None).buffers[0] + + def add_variant(self, name: str, fn: Callable[[TraceContext], Any], *, warmup_runs: Optional[int] = None) -> None: + """Register a traced function. ``fn(ctx)`` runs ttnn ops on ``ctx[...]`` tensors and returns a device tensor, + a :class:`Packed`, or a list / tuple / dict of them (the persistent trace outputs). No host I/O, no + ``synchronize``, no torch ops inside ``fn``: it is called for warm-up and then recorded.""" + self._check_registration(f"variant {name!r}") + if name in self._variants: + raise ValueError(f"variant {name!r} already exists") + self._variants[name] = _Variant(name, fn, self.warmup_runs if warmup_runs is None else int(warmup_runs)) + + def add_eager_warmup(self, fn: Callable[[], Any]) -> None: + """Register eager device work that the model runs *between* replays (host-fallback glue, an eager layout + change of a read-back tensor, ...): ``fn()`` runs once in the first :meth:`capture`, before any trace is + captured, so its programs are compiled -- and their kernel binaries allocated in DRAM -- before the first + capture. A program compiled after a capture shares the address space of the traces' freed intermediates and + a replay can overwrite its binaries (tt-metal ``tech_reports/.../TraceCorrectness.md``: corruption or a + hang); ``TT_METAL_TRACE_ALLOC_TRACKING=1`` reports it.""" + self._check_registration("an eager warm-up") + if self._traces or self._eager_warmed: + raise RuntimeError("add eager warm-ups before the first capture (release() and rebuild)") + self._eager_warmups.append(fn) + + # ------------------------------------------------------------------------------------------ capture + @property + def phases(self) -> int: + """2 when a ping-pong state exists (two traces per variant), else 1.""" + return 2 if any(s.pingpong for s in self._slots.values()) else 1 + + @property + def captured(self) -> bool: + return bool(self._variants) and all((v, p) in self._traces for v in self._variants for p in range(self.phases)) + + def capture(self) -> None: + """Warm up and capture every registered variant that has no trace yet (idempotent). If traces already exist + and a new variant was added, all traces are released, the new variants warmed up, and all recaptured.""" + import ttnn + + self._check_open() + if not self._variants: + raise RuntimeError("no variant registered (add_variant)") + pending = [v for v in self._variants if any((v, p) not in self._traces for p in range(self.phases))] + if not pending: + return + if self._traces: + ttnn.synchronize_device(self.device) # no replay of a trace being released is still in flight + self._release_traces() + warm, pending = pending, list(self._variants) + else: + warm = pending + self._capturing = True + try: + if not self._eager_warmed: + self._warm_eager_programs() + for vname in warm: + t0 = time.perf_counter() + variant = self._variants[vname] + for phase in range(self.phases): + for _ in range(variant.warmup_runs): + ctx = TraceContext(self, vname, phase, capturing=False) + outputs = variant.fn(ctx) + ttnn.synchronize_device(self.device) + self._free_transient(outputs) + self.timings_ms.setdefault(vname, {})["warmup"] = (time.perf_counter() - t0) * 1e3 + self._phase = 0 + self.reset_state() + for vname in pending: + self.timings_ms.setdefault(vname, {})["capture"] = 0.0 + for phase in range(self.phases): + self._capture_one(vname, phase) + finally: + self._capturing = False + ttnn.synchronize_device(self.device) + if self.num_command_queues == 2: + self._op_event = ttnn.record_event(self.device, CQ_COMPUTE) + self._stage_free_event = self._op_event + + def _warm_eager_programs(self) -> None: + """Compile the runner's own eager programs before the first capture: the staging copies (``stage_inputs``), + the state <-> bank copies (``banks``) and the registered eager warm-ups. Contents are kept: a staging buffer + mirrors its input (:meth:`write_input` writes both), and a state and its first bank hold the same value + before the states are reset ahead of the captures.""" + import ttnn + + for slot in self._slots.values(): + if slot.staging is not None: + slot.stage_fn(slot.staging, slot.buffers[0]) + if slot.banks: + ttnn.copy(slot.buffers[0], slot.banks[0]) + ttnn.copy(slot.banks[0], slot.buffers[0]) + for fn in self._eager_warmups: + fn() + ttnn.synchronize_device(self.device) + self._eager_warmed = True + + @contextlib.contextmanager + def _eager(self, what: str) -> Iterator[None]: + """Eager runner work after a capture must not compile a program (see :meth:`add_eager_warmup`).""" + dev = self.device + count = getattr(dev, "num_program_cache_entries", None) + before = count() if (self._traces and count is not None) else None + yield + if before is not None and count() != before: + raise RuntimeError(f"{self.name}: {what} compiled a new program after capture; its kernel binaries share " + "DRAM with the traces' freed intermediates, so a replay can overwrite them. Run it " + "before the first capture (add_eager_warmup) or keep the tensor specs of the warmed " + "program") + + def _capture_one(self, vname: str, phase: int) -> None: + import ttnn + + dev = self.device + variant = self._variants[vname] + ctx = TraceContext(self, vname, phase, capturing=True) + entries_before = dev.num_program_cache_entries() if hasattr(dev, "num_program_cache_entries") else None + forbid = self.forbid_cache_misses and hasattr(dev, "set_program_cache_misses_allowed") + t0 = time.perf_counter() + if forbid: + dev.set_program_cache_misses_allowed(False) + trace_id = ttnn.begin_trace_capture(dev, cq_id=CQ_COMPUTE) + ok = ended = False + try: + outputs = variant.fn(ctx) + ok = True + finally: + try: + ttnn.end_trace_capture(dev, trace_id, cq_id=CQ_COMPUTE) + ended = True + finally: + if forbid: + dev.set_program_cache_misses_allowed(True) + if not (ok and ended): + self._safe_release(trace_id) + try: + entries_after = dev.num_program_cache_entries() if entries_before is not None else None + if entries_before is not None and entries_after != entries_before: + raise RuntimeError(f"{self.name}/{vname}: the program cache grew during capture ({entries_before} -> " + f"{entries_after}); warm-up does not cover the traced graph") + leaves = [] + for path, leaf in _flatten(outputs): + if isinstance(leaf, Packed): + leaves.append((path, leaf.tensor, leaf.layout)) + elif isinstance(leaf, ttnn.Tensor): + leaves.append((path, leaf, None)) + else: + raise TypeError(f"{self.name}/{vname}: output {path} is {type(leaf).__name__}, expected a device " + "tensor or Packed") + if not leaves: + raise ValueError(f"{self.name}/{vname}: the variant returned no output tensor") + pingpong = {s.name for s in self._slots.values() if s.pingpong} + written = ctx.writes & pingpong + if written and written != pingpong: + raise RuntimeError(f"{self.name}/{vname}: writes ping-pong states {sorted(written)} but not " + f"{sorted(pingpong - written)}; a stepping variant must write all of them") + except BaseException: + self._safe_release(trace_id) + raise + if self.alloc_tracking and self._captures > 0: + from ttnn.tools import trace_allocation_tracker as tracker + + keep = self._persistent_addresses() + for _, tensor, _ in leaves: + if _buffer_address(tensor) not in keep: + tracker.acknowledge_corruptible(tensor) + self._captures += 1 + ms = (time.perf_counter() - t0) * 1e3 + self._traces[(vname, phase)] = _Trace(vname, phase, trace_id, outputs, leaves, bool(written), ms) + self.timings_ms[vname]["capture"] += ms + + def _persistent_addresses(self) -> set: + addrs = set() + for slot in self._slots.values(): + for t in slot.tensors(): + a = _buffer_address(t) + if a is not None: + addrs.add(a) + return addrs + + def _deallocate_outputs(self, tensors: Iterator[Any]) -> None: + """Deallocate op-produced output tensors, never a persistent buffer or a view of one. ``force=False``: a + tensor sharing its device memory with another owner (a view of a model weight returned as an output) is + left to its owners -- ``ttnn.deallocate`` forces by default and would free the weight.""" + import ttnn + + keep = self._persistent_addresses() + seen = set() + for tensor in tensors: + if not isinstance(tensor, ttnn.Tensor) or id(tensor) in seen: + continue + seen.add(id(tensor)) + if tensor.is_allocated() and _buffer_address(tensor) not in keep: + ttnn.deallocate(tensor, False) + + def _free_transient(self, outputs: Any) -> None: + """Deallocate warm-up / eager outputs (see :meth:`_deallocate_outputs`).""" + self._deallocate_outputs(leaf.tensor if isinstance(leaf, Packed) else leaf for _, leaf in _flatten(outputs)) + + def _safe_release(self, trace_id) -> None: + import ttnn + + try: + ttnn.release_trace(self.device, trace_id) + except Exception: # noqa: BLE001 -- best effort on an error path; the original error is re-raised + pass + + # -------------------------------------------------------------------------------------------- inputs + def _slot(self, name: str, kind: Optional[str] = None) -> _Slot: + slot = self._slots.get(name) + if slot is None: + raise KeyError(f"{self.name}: no input / param / state named {name!r}") + if kind is not None and slot.kind != kind: + raise KeyError(f"{self.name}: {name!r} is a {slot.kind}, not a {kind}") + return slot + + @staticmethod + def _param_array(slot: _Slot, value: Any) -> np.ndarray: + dt = np.float32 if dtype_name(slot.dtype) in ("float32", "bfloat16", "bfloat8_b", "bfloat4_b") else np.int64 + return np.ascontiguousarray(np.broadcast_to(np.asarray(value, dtype=dt), slot.shape)) + + def _param_bytes(self, slot: _Slot, value: Any) -> bytes: + return self._param_array(slot, value).tobytes() + + def set_params(self, **values: Any) -> None: + """Queue RT-dev parameter values for the next run (uploaded only if they changed).""" + for name in values: + self._slot(name, "param") + self._pending_params.update(values) + + def _collect_uploads(self, inputs: Optional[Mapping[str, Any]], + params: Optional[Mapping[str, Any]]) -> List[Tuple[_Slot, Any, Optional[bytes]]]: + uploads = [] + for name, value in (inputs or {}).items(): + slot = self._slot(name, "input") + uploads.append((slot, to_host_tensor(value, slot.dtype, slot.layout, shape=slot.shape), None)) + merged = dict(self._pending_params) + merged.update(params or {}) + for name, value in merged.items(): + slot = self._slot(name, "param") + arr = self._param_array(slot, value) + key = arr.tobytes() + if key != slot.last_value: + uploads.append((slot, to_host_tensor(arr, slot.dtype, slot.layout), key)) + return uploads + + def _ensure_events(self) -> None: + """2CQ: the CQ0 events CQ1 waits for exist (``capture()`` records them; a partially failed capture, which + leaves earlier variants runnable, does not get that far).""" + import ttnn + + if self._op_event is None: + self._op_event = ttnn.record_event(self.device, CQ_COMPUTE) + if self._stage_free_event is None: + self._stage_free_event = self._op_event + + def _enqueue_uploads(self, uploads: List[Tuple[_Slot, Any, Optional[bytes]]]) -> None: + import ttnn + + if uploads: + if self.num_command_queues == 1: + for slot, host, _ in uploads: + ttnn.copy_host_to_device_tensor(host, slot.buffers[0], cq_id=CQ_COMPUTE) + elif self.stage_inputs: + self._ensure_events() + ttnn.wait_for_event(CQ_INPUT, self._stage_free_event) + for slot, host, _ in uploads: + ttnn.copy_host_to_device_tensor(host, slot.staging, cq_id=CQ_INPUT) + written = ttnn.record_event(self.device, CQ_INPUT) + ttnn.wait_for_event(CQ_COMPUTE, written) + with self._eager("a stage_fn copy"): + for slot, _, _ in uploads: + slot.stage_fn(slot.staging, slot.buffers[0]) + self._stage_free_event = ttnn.record_event(self.device, CQ_COMPUTE) + else: + self._ensure_events() + ttnn.wait_for_event(CQ_INPUT, self._op_event) + for slot, host, _ in uploads: + ttnn.copy_host_to_device_tensor(host, slot.buffers[0], cq_id=CQ_INPUT) + written = ttnn.record_event(self.device, CQ_INPUT) + ttnn.wait_for_event(CQ_COMPUTE, written) + for slot, _, key in uploads: + if key is not None: + slot.last_value = key + self._pending_params.clear() + + def write_input(self, name: str, value: Any) -> None: + """Upload ``value`` into input ``name`` now (CQ0, outside any trace): e.g. a realistic warm-up sample. + With 2 CQs the event that later CQ1 uploads wait for is re-recorded after this write, so an upload of the + next frame can never land before it (both write the same buffer from different queues).""" + import ttnn + + self._check_open() + slot = self._slot(name, "input") + host = to_host_tensor(value, slot.dtype, slot.layout, shape=slot.shape) + ttnn.copy_host_to_device_tensor(host, slot.buffers[0], cq_id=CQ_COMPUTE) + if slot.staging is not None: # the staging buffer mirrors the input (the stage-copy warm-up keeps it) + ttnn.copy_host_to_device_tensor(host, slot.staging, cq_id=CQ_COMPUTE) + if self.num_command_queues == 2 and self._op_event is not None: + self._op_event = ttnn.record_event(self.device, CQ_COMPUTE) + if self.stage_inputs: + self._stage_free_event = self._op_event + + # --------------------------------------------------------------------------------------------- run + def _trace_for(self, variant: Optional[str], phase: Optional[int] = None) -> _Trace: + self._check_open() + name = variant or self._last_variant or (next(iter(self._variants)) if len(self._variants) == 1 else None) + if name is None: + raise ValueError("variant name required") + if name not in self._variants: + raise KeyError(f"{self.name}: unknown variant {name!r}; have {sorted(self._variants)}") + p = self._phase if phase is None else phase + trace = self._traces.get((name, p)) + if trace is None: + raise RuntimeError(f"{self.name}: variant {name!r} is not captured; call capture() first") + return trace + + def _execute(self, trace: _Trace) -> None: + import ttnn + + ttnn.execute_trace(self.device, trace.trace_id, cq_id=CQ_COMPUTE, blocking=False) + if self.num_command_queues == 2: + self._op_event = ttnn.record_event(self.device, CQ_COMPUTE) + trace.done_event = self._op_event + self._last_variant = trace.variant + self._last_phase[trace.variant] = trace.phase + self._runs += 1 + if trace.steps: + self._phase ^= 1 + + def upload(self, inputs: Optional[Mapping[str, Any]] = None, params: Optional[Mapping[str, Any]] = None) -> int: + """Enqueue the uploads of ``inputs`` and changed ``params`` (CQ0, or CQ1 + events with 2 CQs) without + replaying anything; the next :meth:`run` / :meth:`replay` consumes them. Returns the number of tensors + uploaded.""" + self._check_open() + if not self.captured: + raise RuntimeError(f"{self.name}: capture() before uploading") + uploads = self._collect_uploads(inputs, params) + self._enqueue_uploads(uploads) + return len(uploads) + + def run(self, variant: Optional[str] = None, inputs: Optional[Mapping[str, Any]] = None, + params: Optional[Mapping[str, Any]] = None): + """Upload ``inputs`` (name -> numpy / torch / ttnn host tensor) and changed ``params``, then replay the + variant's trace without blocking. Returns its device outputs (valid once the replay finished).""" + trace = self._trace_for(variant) + self._enqueue_uploads(self._collect_uploads(inputs, params)) + self._execute(trace) + return trace.outputs + + def replay(self, variant: Optional[str] = None, n: int = 1) -> None: + """Replay ``n`` times with no uploads (back-to-back device timing); honours ping-pong phases.""" + for _ in range(n): + self._execute(self._trace_for(variant)) + + def outputs(self, variant: Optional[str] = None, phase: Optional[int] = None): + """Device outputs of a variant's trace (default: the phase that ran last for it, else phase 0).""" + name = variant or self._last_variant + if phase is None and name is not None: + phase = self._last_phase.get(name, 0) + return self._trace_for(name, phase if phase is not None else 0).outputs + + def read(self, variant: Optional[str] = None, *, cq_id: int = CQ_COMPUTE, as_torch: bool = False, + leaves: Optional[Iterable[int]] = None): + """Read the outputs of the last run of ``variant`` into preallocated host tensors (blocking). + + Returns the output structure with numpy arrays (``as_torch=True``: torch tensors); a :class:`Packed` leaf + becomes ``{name: array}``. ``cq_id=1`` (2CQ) waits on the host for the trace's completion event and reads on + CQ1, so CQ0 can already replay the next segment (segmented D2H). ``leaves`` (0.24.3): indices of the output + leaves to read (flattened output order, e.g. the positions of a list output); the others come back as None + (no transfer). A later ``read(leaves=...)`` of the same run reads the rest, as long as no other run of the + trace happened in between (:attr:`runs`).""" + import ttnn + + name = variant or self._last_variant + if name is None or name not in self._last_phase: + raise RuntimeError(f"{self.name}: variant {name!r} has not run yet") + trace = self._trace_for(name, self._last_phase[name]) + if cq_id not in (CQ_COMPUTE, CQ_INPUT): + raise ValueError(f"cq_id={cq_id}: expected 0 or 1") + if cq_id == CQ_INPUT: + if self.num_command_queues != 2: + raise ValueError("cq_id=1 needs a device opened with 2 command queues") + ttnn.event_synchronize(trace.done_event) + if trace.host_buffers is None: + trace.host_buffers = [ttnn.allocate_tensor_on_host(t.spec, self.device) for _, t, _ in trace.leaves] + want = None if leaves is None else {int(i) for i in leaves} + if want is not None and any(i < 0 or i >= len(trace.leaves) for i in want): + raise IndexError(f"{self.name}: leaves {sorted(want)} out of range (0..{len(trace.leaves) - 1})") + values: Dict[Tuple, Any] = {} + for li, ((path, tensor, layout), host) in enumerate(zip(trace.leaves, trace.host_buffers)): + if want is not None and li not in want: + values[path] = None + continue + arr = None + if self.read_view and tensor.layout == ttnn.ROW_MAJOR_LAYOUT: + fresh = ttnn.allocate_tensor_on_host(tensor.spec, self.device) + ttnn.copy_device_to_host_tensor(tensor, fresh, blocking=True, cq_id=cq_id) + arr = host_view(fresh) + if arr is None: + arr = to_numpy(fresh) + if arr is None: + ttnn.copy_device_to_host_tensor(tensor, host, blocking=True, cq_id=cq_id) + arr = to_numpy(host) + value: Any = layout.unpack(arr) if layout is not None else arr + if as_torch: + import torch + + value = ({k: torch.from_numpy(np.ascontiguousarray(v)) for k, v in value.items()} + if isinstance(value, dict) else torch.from_numpy(np.ascontiguousarray(value))) + values[path] = value + structure = trace.outputs + if isinstance(structure, Packed) or not isinstance(structure, (Mapping, list, tuple)): + return values[()] + return _rebuild(structure, values) + + def __call__(self, variant: Optional[str] = None, inputs: Optional[Mapping[str, Any]] = None, + params: Optional[Mapping[str, Any]] = None, *, as_torch: bool = False, + leaves: Optional[Iterable[int]] = None): + """``run`` + ``read`` (the common synchronous path; ``leaves``: :meth:`read`'s partial read, 0.24.3).""" + self.run(variant, inputs, params) + return self.read(variant, as_torch=as_torch, leaves=leaves) + + def run_eager(self, variant: Optional[str] = None, inputs: Optional[Mapping[str, Any]] = None, + params: Optional[Mapping[str, Any]] = None): + """Upload, run the variant's function *eagerly* (no trace) and return its outputs read to numpy, freeing + every eager buffer before returning (safe next to captured traces). State writes happen as in a replay. + Use it for replay-vs-eager bit checks.""" + import ttnn + + self._check_open() + name = variant or self._last_variant or (next(iter(self._variants)) if self._variants else None) + if name not in self._variants: + raise KeyError(f"{self.name}: unknown variant {name!r}; have {sorted(self._variants)}") + variant_obj = self._variants[name] + uploads = self._collect_uploads(inputs, params) + for slot, host, key in uploads: + ttnn.copy_host_to_device_tensor(host, slot.buffers[0], cq_id=CQ_COMPUTE) + if key is not None: + slot.last_value = key + self._pending_params.clear() + ctx = TraceContext(self, name, self._phase, capturing=False) + with self._eager(f"run_eager({name!r})"): + outputs = variant_obj.fn(ctx) + values = {} + for path, leaf in _flatten(outputs): + if isinstance(leaf, Packed): + values[path] = leaf.layout.unpack(to_numpy(leaf.tensor)) + else: + values[path] = to_numpy(leaf) + self._free_transient(outputs) + pingpong = {s.name for s in self._slots.values() if s.pingpong} + if pingpong and (ctx.writes & pingpong) == pingpong: + self._phase ^= 1 + if isinstance(outputs, Packed) or not isinstance(outputs, (Mapping, list, tuple)): + return values[()] + return _rebuild(outputs, values) + + # ------------------------------------------------------------------------------------------- state + @property + def runs(self) -> int: + """0.24.3: the number of trace replays run so far (:meth:`run` / :meth:`__call__`; a ``read(leaves=...)`` of + the remaining leaves of a run is valid while this has not changed).""" + return self._runs + + @property + def phase(self) -> int: + """Which buffer of each ping-pong state the next run reads (0 = the first buffer).""" + return self._phase + + def state_buffer(self, name: str): + """The device buffer the next run reads for state ``name`` (ping-pong: the buffer of the current + :attr:`phase`).""" + slot = self._slot(name, "state") + return slot.buffers[self._phase] if slot.pingpong else slot.buffers[0] + + def reset_state(self, name: Optional[str] = None, value: Any = None) -> None: + """Write the initial value (or ``value``) of state ``name`` (all states when ``None``) into the buffer the + next run reads. ``value``: numpy / scalar / torch / ttnn host tensor (uploaded) or a ttnn *device* tensor of + the same shape (``ttnn.copy`` on the device). Enqueued on CQ0, so it lands after any replay already + enqueued.""" + import ttnn + + self._check_open() + names = [name] if name is not None else [s.name for s in self._slots.values() if s.kind == "state"] + for n in names: + slot = self._slot(n, "state") + target = self.state_buffer(n) + if isinstance(value, ttnn.Tensor) and value.storage_type() == ttnn.StorageType.DEVICE: + _check_copy(f"reset_state({n!r})", value, slot) + with self._eager(f"reset_state({n!r}) from a device tensor"): + ttnn.copy(value, target) + continue + if value is None: + host = slot.init + elif isinstance(value, ttnn.Tensor): + host = to_host_tensor(value, slot.dtype, slot.layout, shape=slot.shape) + else: + arr = to_numpy(value) if hasattr(value, "detach") else np.asarray(value) + host = to_host_tensor(np.broadcast_to(arr, slot.shape), slot.dtype, slot.layout) + ttnn.copy_host_to_device_tensor(host, target, cq_id=CQ_COMPUTE) + + def read_state(self, name: str) -> np.ndarray: + """The value the next run will read for state ``name`` (blocking read on CQ0).""" + return to_numpy(self.state_buffer(name)) + + def _bank(self, name: str, bank: int): + slot = self._slot(name, "state") + if not 0 <= bank < len(slot.banks): + raise IndexError(f"{self.name}: state {name!r} has {len(slot.banks)} bank(s) (add_state(banks=...)), " + f"not bank {bank}") + return slot.banks[bank] + + def save_state(self, name: str, bank: int) -> None: + """Copy the current value of state ``name`` into its ``bank`` (``ttnn.copy`` on CQ0, eager, after any + replay already enqueued): the first half of a stream switch (PLAN.md D16; :class:`StreamBanks`).""" + import ttnn + + self._check_open() + with self._eager(f"save_state({name!r})"): + ttnn.copy(self.state_buffer(name), self._bank(name, bank)) + + def load_state(self, name: str, bank: int) -> None: + """Copy ``bank`` back into the buffer the next run reads for state ``name`` (``ttnn.copy`` on CQ0).""" + import ttnn + + self._check_open() + with self._eager(f"load_state({name!r})"): + ttnn.copy(self._bank(name, bank), self.state_buffer(name)) + + # ------------------------------------------------------------------------------------------- misc + def trace_ids(self) -> Dict[Tuple[str, int], Any]: + """``{(variant, phase): trace_id}`` for profiling scripts.""" + return {k: t.trace_id for k, t in self._traces.items()} + + def describe(self) -> Dict[str, Any]: + """A JSON-able summary for ``model.info`` / OPT_BASELINE.""" + def spec(s: _Slot) -> Dict[str, Any]: + return {"shape": list(s.shape), "dtype": dtype_name(s.dtype), "layout": str(s.layout).rsplit(".", 1)[-1], + **({"pingpong": s.pingpong, "banks": len(s.banks)} if s.kind == "state" else {})} + + entries = None + if hasattr(self.device, "num_program_cache_entries"): + entries = int(self.device.num_program_cache_entries()) + return { + "name": self.name, "num_command_queues": self.num_command_queues, "stage_inputs": self.stage_inputs, + "warmup_runs": self.warmup_runs, "phases": self.phases, "alloc_tracking": self.alloc_tracking, + "read_view": self.read_view, "variants": sorted(self._variants), "traces": len(self._traces), + "inputs": {s.name: spec(s) for s in self._slots.values() if s.kind == "input"}, + "params": {s.name: spec(s) for s in self._slots.values() if s.kind == "param"}, + "states": {s.name: spec(s) for s in self._slots.values() if s.kind == "state"}, + "outputs": {s.name: spec(s) for s in self._slots.values() if s.kind == "output"}, + "timings_ms": {k: {kk: round(vv, 3) for kk, vv in v.items()} for k, v in self.timings_ms.items()}, + "program_cache_entries": entries, + } + + def _release_traces(self) -> None: + traces, self._traces = self._traces, {} + for trace in traces.values(): + self._safe_release(trace.trace_id) + self._last_phase.clear() + self._last_variant = None + self._captures = 0 + self._deallocate_outputs(tensor for trace in traces.values() for _, tensor, _ in trace.leaves) + + def release(self) -> None: + """Release every trace and deallocate the persistent tensors. Idempotent; the persistent tensors are freed + even when the device sync or a trace release raises (the error propagates afterwards).""" + import ttnn + + if self._closed: + return + self._closed = True + try: + try: + ttnn.synchronize_device(self.device) + finally: + self._release_traces() + finally: + slots, self._slots = list(self._slots.values()), {} + for slot in slots: + for t in slot.tensors(): + if t.is_allocated(): + ttnn.deallocate(t) + + def _check_open(self) -> None: + if self._closed: + raise RuntimeError(f"{self.name}: the TraceRunner was released") + + def __enter__(self) -> "TraceRunner": + return self + + def __exit__(self, *exc) -> None: + self.release() + + +class StreamBanks: + """Per-stream device state of a temporal model (PLAN.md D16) on top of the states of a :class:`TraceRunner`. + + The traces read and write one set of state buffers: the *active* stream's. With ``max_streams > 1`` every known + stream id owns one bank of each state (``add_state(..., banks=max_streams)``) and a switch saves the active + stream into its bank and loads the selected one (``ttnn.copy`` on CQ0, after the replays already enqueued; + probe P13 measured ~80 us eager for a StreamPETR-size state). A new id beyond ``max_streams`` is refused + (``on_full="reject"``: :class:`~.io.InputError`, HTTP 400) or takes over the least recently used stream + (``"evict"``; with ``max_streams=1`` that simply restarts the one state). A stream starts fresh -- its states + reset to their ``init`` values -- when it is new, when ``reset=True``, or when its timestamp goes backwards or + jumps by more than ``max_gap_s``; :meth:`select` returns True then, so the model can also set its first-frame + RT-dev params (BEVFormer ``use_prev_bev=0``, BEVDet ``flag``, ...). Create it after the last ``capture()`` (a + capture resets every state) and call :meth:`select` under the model lock, before the run of each frame:: + + S_MAX = 1 # first publish (D16) + runner.add_state("prev_bev", shape=(1, 1, 22500, 256), dtype="bfloat16", pingpong=True, + banks=S_MAX if S_MAX > 1 else 0) + streams = StreamBanks(runner, ["prev_bev"], max_streams=S_MAX, on_full="evict", max_gap_s=2.0) + ... + fresh = streams.select(stream.get("id", "default"), reset=stream.get("reset", False), + timestamp_s=stream.get("timestamp_s")) + out = runner("frame", inputs=..., params={"use_prev_bev": 0.0 if fresh else 1.0}) + """ + + def __init__(self, runner: TraceRunner, states: Sequence[str], *, max_streams: int = 1, on_full: str = "reject", + max_gap_s: Optional[float] = None): + if int(max_streams) < 1: + raise ValueError("max_streams must be >= 1") + if on_full not in ("reject", "evict"): + raise ValueError(f"on_full={on_full!r}: expected 'reject' or 'evict'") + self.runner = runner + self.states = tuple(states) + if not self.states: + raise ValueError("StreamBanks needs at least one state") + self.max_streams = int(max_streams) + for name in self.states: + banks = len(runner._slot(name, "state").banks) + if self.max_streams > 1 and banks < self.max_streams: + raise ValueError(f"state {name!r} has {banks} bank(s); StreamBanks(max_streams={self.max_streams}) " + f"needs add_state(..., banks={self.max_streams})") + self.on_full = on_full + self.max_gap_s = None if max_gap_s is None else float(max_gap_s) + self.active: Optional[str] = None + self._bank: Dict[str, int] = {} # stream id -> bank index (max_streams > 1) + self._last_t: Dict[str, float] = {} # stream id -> timestamp of its last frame + self._used: Dict[str, int] = {} # stream id -> last use (LRU clock) + self._clock = 0 + + @property + def streams(self) -> List[str]: + """Known stream ids, most recently used first.""" + return sorted(self._used, key=lambda s: -self._used[s]) + + def _save_active(self) -> None: + if self.active is not None and self.active in self._bank: + for name in self.states: + self.runner.save_state(name, self._bank[self.active]) + + def forget(self, stream_id: str) -> None: + """Drop a stream (its bank becomes free; if it was active, the next :meth:`select` starts fresh).""" + sid = str(stream_id) + self._used.pop(sid, None) + self._bank.pop(sid, None) + self._last_t.pop(sid, None) + if self.active == sid: + self.active = None + + def select(self, stream_id: Any = "default", *, reset: bool = False, timestamp_s: Optional[float] = None) -> bool: + """Make ``stream_id`` the active stream for the next run; returns True when its state starts fresh.""" + sid = str(stream_id) + fresh = bool(reset) + if sid != self.active: + if sid in self._used: # a known stream parked in its bank + self._save_active() + if not fresh: + for name in self.states: + self.runner.load_state(name, self._bank[sid]) + else: # a new stream + if len(self._used) >= self.max_streams: + if self.on_full == "reject": + raise InputError(f"stream {sid!r}: this model keeps device state for {self.max_streams} " + f"stream(s), in use by {self.streams}; reuse an id") + self.forget(min(self._used, key=self._used.__getitem__)) + self._save_active() + if self.max_streams > 1: + self._bank[sid] = min(set(range(self.max_streams)) - set(self._bank.values())) + fresh = True + self.active = sid + if not fresh and timestamp_s is not None and self.max_gap_s is not None and sid in self._last_t: + dt = float(timestamp_s) - self._last_t[sid] + fresh = dt < 0 or dt > self.max_gap_s + if fresh: + for name in self.states: + self.runner.reset_state(name) + if timestamp_s is not None: + self._last_t[sid] = float(timestamp_s) + elif fresh: + self._last_t.pop(sid, None) + self._clock += 1 + self._used[sid] = self._clock + return fresh + + def describe(self) -> Dict[str, Any]: + """JSON-able summary for ``model.info``.""" + return {"max_streams": self.max_streams, "on_full": self.on_full, "max_gap_s": self.max_gap_s, + "states": list(self.states), "active": self.active, "streams": self.streams} diff --git a/code/tt_depthpro2/ttaw/voxelize.py b/code/tt_depthpro2/ttaw/voxelize.py new file mode 100644 index 0000000000000000000000000000000000000000..755df00522b42786343b105b06cce7f76defea92 --- /dev/null +++ b/code/tt_depthpro2/ttaw/voxelize.py @@ -0,0 +1,260 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C12 voxelization: deterministic pillar builders (vectorised numpy), Autoware's pillar feature decoration, and the +two canvas forms of the PointPillars scatter (dense scatter for references, gather index for the device). + +Autoware's CUDA voxelizer (``autoware_lidar_centerpoint/lib/preprocess/preprocess_kernel.cu``) is +non-deterministic: slots inside a pillar come from ``atomicAdd`` over a randomly shuffled point buffer and pillar +ids from ``atomicAdd`` over a 2-D thread grid (S:centerpoint:177-186). The ports replace it by a deterministic +policy with the same statistics (PLAN.md D1, S:centerpoint:381-389): + +1. optional seeded permutation of the input rows (:func:`ttaw.pointcloud.seeded_permutation`); +2. the half-open range test and the cell index ``floor((v - min) / voxel)`` (a float32 *division*, clamped; the + kernel's ``:135-145``); +3. the first ``max_points_per_pillar`` points of every cell in (permuted) input order; +4. pillar ids in ascending cell order, keeping the first ``max_pillars``. The cell order is ``"flipped_x"`` + (CenterPoint: ``cell = (grid_x - 1 - ix) * grid_y + iy``, front rows first, ``:144``) or ``"raster"`` + (PointPainting: ``cell = iy * grid_x + ix``, S:pointpainting:229-232). + +The result (:class:`PillarSet`) holds the raw rows of every kept slot (zero-padded), the point counts and the +``(z, y, x)`` = ``(0, iy, ix)`` coordinates of mmdet3d / the CUDA ``uint3 {0, idy, idx}`` (``:189-190``). + +:func:`decorate_pillar_features` is ``generateFeatures_kernel`` (``:211-343``) for 9 / 10 / 11 encoder features +(the cluster mean is summed slot by slot in float32, a fixed order standing in for the kernel's float atomics; the +pillar centre is ``voxel / 2 + coord * voxel + min`` in float32; padded slots are all zero). + +Canvas: :func:`scatter_canvas` is ``scatterFeatures_kernel`` (``scatter_kernel.cu:25-48``: ``canvas[c, iy, ix]``). +The device builds the same canvas as a *gather* (C19, probe P4): :func:`canvas_gather_index` gives, for every cell +``iy * grid_x + ix`` of the NHWC canvas, the row of its pillar or a sentinel row (an explicit zero row of the +feature table), so the canvas is ``table[index]`` with no scatter, no clear and a static shape. + +numpy only; no side effects on import. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Dict, Optional, Sequence, Tuple + +import numpy as np + +from .pointcloud import seeded_permutation + +__all__ = [ + "PillarGridSpec", + "PillarSet", + "assign_pillars", + "decorate_pillar_features", + "scatter_canvas", + "canvas_gather_index", + "pillar_cell_index", +] + +_ORDERS = ("flipped_x", "raster") + + +@dataclass(frozen=True) +class PillarGridSpec: + """A pillar grid and its capacities. Ranges and sizes are float32, as the CUDA config stores them + (``centerpoint_config.hpp:41-56``); ``grid_x = int((max_x - min_x) / voxel_x)`` in float32 (``:95-97``).""" + + range_min: Tuple[float, float, float] + range_max: Tuple[float, float, float] + voxel_size: Tuple[float, float, float] + max_points_per_pillar: int = 32 + max_pillars: int = 40000 + order: str = "flipped_x" + + def __post_init__(self) -> None: + if self.order not in _ORDERS: + raise ValueError(f"order must be one of {_ORDERS}, got {self.order!r}") + if self.max_points_per_pillar < 1 or self.max_pillars < 1: + raise ValueError("capacities must be >= 1") + + @property + def min_f32(self) -> np.ndarray: + return np.asarray(self.range_min, dtype=np.float32) + + @property + def max_f32(self) -> np.ndarray: + return np.asarray(self.range_max, dtype=np.float32) + + @property + def voxel_f32(self) -> np.ndarray: + return np.asarray(self.voxel_size, dtype=np.float32) + + def _grid(self, axis: int) -> int: + return int(np.float32(self.max_f32[axis] - self.min_f32[axis]) / self.voxel_f32[axis]) + + @property + def grid_x(self) -> int: + return self._grid(0) + + @property + def grid_y(self) -> int: + return self._grid(1) + + @property + def grid_z(self) -> int: + return self._grid(2) + + @property + def num_cells(self) -> int: + return self.grid_x * self.grid_y + + +@dataclass +class PillarSet: + """The deterministic voxelization of one cloud (fixed capacity ``max_pillars``; rows past ``num_pillars`` are + zero).""" + + points: np.ndarray # (max_pillars, K, F) float32: raw rows of the kept slots, zero-padded + num_points: np.ndarray # (max_pillars,) int32: min(count, K), 0 for unused rows + coords: np.ndarray # (max_pillars, 3) int32: (0, iy, ix) + num_pillars: int # kept pillars (<= max_pillars) + num_pillars_total: int # non-empty cells before the cap (Autoware's num_voxels counter) + num_points_in_range: int + max_points_in_pillar: int # largest per-cell count before the slot cap + pillars_over_cap: int # cells holding more than K points + num_points_input: int + + @property + def overflow(self) -> bool: + """More non-empty cells than ``max_pillars``: the farthest-back pillars were dropped.""" + return self.num_pillars_total > self.points.shape[0] + + def stats(self) -> Dict[str, Any]: + return {"num_points": self.num_points_input, "num_points_in_range": self.num_points_in_range, + "num_pillars": self.num_pillars, "num_pillars_total": self.num_pillars_total, + "max_points_in_pillar": self.max_points_in_pillar, "pillars_over_cap": self.pillars_over_cap, + "pillar_overflow": self.overflow} + + +def pillar_cell_index(points: np.ndarray, spec: PillarGridSpec) -> Tuple[np.ndarray, np.ndarray]: + """``(ix, iy)`` int64 of each row: ``floor((v - min) / voxel)`` evaluated in float32, clamped to the grid + (``preprocess_kernel.cu:140-143``). The caller has already applied the range test.""" + p = np.asarray(points, dtype=np.float32) + mn, vs = spec.min_f32, spec.voxel_f32 + ix = np.floor((p[:, 0] - mn[0]) / vs[0]).astype(np.int64) + iy = np.floor((p[:, 1] - mn[1]) / vs[1]).astype(np.int64) + return np.clip(ix, 0, spec.grid_x - 1), np.clip(iy, 0, spec.grid_y - 1) + + +def _cell_key(ix: np.ndarray, iy: np.ndarray, spec: PillarGridSpec) -> np.ndarray: + if spec.order == "flipped_x": + return (spec.grid_x - 1 - ix) * spec.grid_y + iy + return iy * spec.grid_x + ix + + +def _key_to_ixy(key: np.ndarray, spec: PillarGridSpec) -> Tuple[np.ndarray, np.ndarray]: + if spec.order == "flipped_x": + return (spec.grid_x - 1) - key // spec.grid_y, key % spec.grid_y + return key % spec.grid_x, key // spec.grid_x + + +def assign_pillars(points: np.ndarray, spec: PillarGridSpec, *, shuffle_seed: Optional[int] = None) -> PillarSet: + """Deterministic voxelization (module docstring). ``points``: (N, F) float32 in the model frame, x, y, z in + columns 0-2 (the remaining columns, e.g. time_lag, are copied into the slots). Rows with a non-finite x, y or z + never enter a pillar.""" + pts = np.ascontiguousarray(np.asarray(points, dtype=np.float32)) + if pts.ndim != 2 or pts.shape[1] < 3: + raise ValueError(f"points must be (N, >=3), got {pts.shape}") + n_in = len(pts) + perm = seeded_permutation(n_in, shuffle_seed) + if perm is not None: + pts = pts[perm] + mn, mx = spec.min_f32, spec.max_f32 + keep = np.ones(len(pts), dtype=bool) + for a in range(3): # Autoware: reject x < min || x >= max (NaN would pass there; here it fails) + keep &= (pts[:, a] >= mn[a]) & (pts[:, a] < mx[a]) + pts = pts[keep] + ix, iy = pillar_cell_index(pts, spec) + key = _cell_key(ix, iy, spec) + order = np.argsort(key, kind="stable") # stable: input order inside each cell + key_sorted = key[order] + uniq, first, counts = np.unique(key_sorted, return_index=True, return_counts=True) + slot = np.arange(len(key_sorted)) - np.repeat(first, counts) + K, P = spec.max_points_per_pillar, spec.max_pillars + n_total = int(len(uniq)) + n_keep = min(n_total, P) + pid = np.repeat(np.arange(n_total), counts) # pillar id of every sorted row (ascending cell order) + sel = (slot < K) & (pid < n_keep) + F = pts.shape[1] + raw = np.zeros((P, K, F), dtype=np.float32) + raw[pid[sel], slot[sel]] = pts[order][sel] + num = np.zeros(P, dtype=np.int32) + num[:n_keep] = np.minimum(counts[:n_keep], K) + cx, cy = _key_to_ixy(uniq[:n_keep], spec) + coords = np.zeros((P, 3), dtype=np.int32) + coords[:n_keep, 1] = cy + coords[:n_keep, 2] = cx + return PillarSet(points=raw, num_points=num, coords=coords, num_pillars=n_keep, num_pillars_total=n_total, + num_points_in_range=int(keep.sum()), max_points_in_pillar=int(counts.max()) if n_total else 0, + pillars_over_cap=int((counts > K).sum()), num_points_input=n_in) + + +def decorate_pillar_features(pillars: PillarSet, spec: PillarGridSpec, *, encoder_in_feature_size: int = 9, + point_dim: Optional[int] = None) -> np.ndarray: + """``generateFeatures_kernel`` (``preprocess_kernel.cu:211-343``) -> (max_pillars, K, encoder_in_feature_size) + float32. ``point_dim`` (columns copied from the raw rows) is 5 (x, y, z, intensity, time_lag) for 11 features + and 4 (x, y, z, time_lag) otherwise, as the kernel's ``point_dim``. Layouts: + + - 9: x, y, z, t, x-x̄, y-ȳ, z-z̄, x-x_c, y-y_c + - 10: x, y, z, t, x-x̄, y-ȳ, z-z̄, x-x_c, y-y_c, z-z_c + - 11: x, y, z, i, t, x-x̄, y-ȳ, z-z̄, x-x_c, y-y_c, z-z_c + + x̄ is the mean of the pillar's kept points (summed slot by slot in float32, divided by the float count); + ``x_c = voxel_x / 2 + ix * voxel_x + min_x`` in float32 (``:269-276``). Padded slots and unused pillars are 0.""" + F_enc = int(encoder_in_feature_size) + if F_enc not in (9, 10, 11): + raise ValueError("encoder_in_feature_size must be 9, 10 or 11") + pd = (5 if F_enc >= 11 else 4) if point_dim is None else int(point_dim) + raw = pillars.points + P, K, F = raw.shape + if F < pd: + raise ValueError(f"pillar rows have {F} columns, decoration needs {pd}") + n = pillars.num_pillars + out = np.zeros((P, K, F_enc), dtype=np.float32) + if n == 0: + return out + r = raw[:n] + cnt = pillars.num_points[:n].astype(np.float32) + s = np.zeros((n, 3), dtype=np.float32) + for k in range(K): # fixed slot order (the kernel's float atomicAdd order is unspecified) + s += r[:, k, :3] + mean = s / cnt[:, None] + vs, mn = spec.voxel_f32, spec.min_f32 + half = vs / np.float32(2) + xo = (half[0] + pillars.coords[:n, 2].astype(np.float32) * vs[0]) + mn[0] + yo = (half[1] + pillars.coords[:n, 1].astype(np.float32) * vs[1]) + mn[1] + zo = (half[2] + pillars.coords[:n, 0].astype(np.float32) * vs[2]) + mn[2] + f = out[:n] + f[:, :, :pd] = r[:, :, :pd] + f[:, :, pd:pd + 3] = r[:, :, :3] - mean[:, None, :] + f[:, :, pd + 3] = r[:, :, 0] - xo[:, None] + f[:, :, pd + 4] = r[:, :, 1] - yo[:, None] + if F_enc in (10, 11): + f[:, :, pd + 5] = r[:, :, 2] - zo[:, None] + valid = np.arange(K)[None, :] < pillars.num_points[:n, None] + f[~valid] = 0.0 + return out + + +def scatter_canvas(features: np.ndarray, coords: np.ndarray, num_pillars: int, spec: PillarGridSpec) -> np.ndarray: + """``scatterFeatures_kernel``: ``canvas[c, iy, ix] = features[p, c]`` for the first ``num_pillars`` rows; the + canvas is (C, grid_y, grid_x) float32 and zero elsewhere (NCHW without the batch axis).""" + f = np.asarray(features, dtype=np.float32).reshape(np.shape(features)[0], -1) + C = f.shape[1] + canvas = np.zeros((C, spec.grid_y, spec.grid_x), dtype=np.float32) + c = np.asarray(coords)[:num_pillars] + canvas[:, c[:, 1], c[:, 2]] = f[:num_pillars].T + return canvas + + +def canvas_gather_index(coords: np.ndarray, num_pillars: int, spec: PillarGridSpec, *, sentinel: int, + dtype: Any = np.uint32) -> np.ndarray: + """Gather form of the scatter (C19): for every cell ``iy * grid_x + ix`` of the row-major (NHWC) canvas, the row + of its pillar, or ``sentinel`` (an all-zero row of the feature table) for an empty cell. Then + ``canvas_nhwc = table[index]`` equals :func:`scatter_canvas` transposed to (grid_y, grid_x, C).""" + idx = np.full(spec.num_cells, sentinel, dtype=np.int64) + c = np.asarray(coords)[:num_pillars] + idx[c[:, 1].astype(np.int64) * spec.grid_x + c[:, 2].astype(np.int64)] = np.arange(num_pillars) + return idx.astype(dtype) diff --git a/code/tt_depthpro2/ttaw/weights.py b/code/tt_depthpro2/ttaw/weights.py new file mode 100644 index 0000000000000000000000000000000000000000..4f7dd87a2d28408db9bb3d8b0cf377343b2bcd03 --- /dev/null +++ b/code/tt_depthpro2/ttaw/weights.py @@ -0,0 +1,632 @@ +# SPDX-License-Identifier: Apache-2.0 +"""C04: weights -- ONNX initializers addressed by the node that consumes them, BN folding in float64, safetensors / +``.pth`` loading, and an on-disk cache of prepared (tilized, converted) device tensors. + +Why by consuming node: initializer names drift between exports of the same network (FRNet), and MatMul weights are +often anonymous (``onnx::MatMul_1234`` in Diffusion Planner), while node names (``/backbone/conv1/Conv``) are stable. +``OnnxWeights`` parses the graph as data only (no onnxruntime, no execution); external-data paths must stay inside +the model's directory. + +BN folding: every fold is computed in float64 and rounded once at the end (default float32; pass ``dtype=None`` to +keep float64 and round straight to the device dtype later). + +The device cache stores ``ttnn`` host tensors (``.tensorbin``) under ``$TT_CACHE_PATH`` (the tt-model container +mounts it at ``/tensor-cache``) or ``~/.cache/ttaw``, keyed by a digest of the source weights, so a new weights +revision never reuses stale tensors. ``TTAW_WEIGHT_CACHE=0`` disables it (A/B switch, read when the cache is built). + +Only ``numpy`` is imported at module level; ``onnx``, ``safetensors``, ``torch`` and ``ttnn`` are imported by the +functions that need them. +""" +from __future__ import annotations + +import fnmatch +import hashlib +import os +import re +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Dict, Iterator, List, Mapping, Optional, Tuple, Union + +import numpy as np + +__all__ = [ + "BatchNorm", + "fold_bn", + "fold_bn_conv", + "fold_bn_linear", + "fold_bn_conv_transpose", + "OnnxNode", + "ConvParams", + "GemmParams", + "OnnxWeights", + "StateDict", + "load_safetensors", + "load_torch_checkpoint", + "load_state_dict", + "file_sha256", + "cache_root", + "WeightCache", +] + +PathLike = Union[str, os.PathLike] + + +# ---------------------------------------------------------------------------------------------- BN folding + +@dataclass(frozen=True) +class BatchNorm: + """Inference BatchNorm parameters (any of BN1d / BN2d / ONNX BatchNormalization), stored in float64.""" + + gamma: np.ndarray + beta: np.ndarray + mean: np.ndarray + var: np.ndarray + eps: float = 1e-5 + + def __post_init__(self) -> None: + for name in ("gamma", "beta", "mean", "var"): + object.__setattr__(self, name, np.asarray(getattr(self, name), dtype=np.float64).reshape(-1)) + n = self.gamma.shape[0] + if not (self.beta.shape[0] == self.mean.shape[0] == self.var.shape[0] == n): + raise ValueError("BatchNorm parameter lengths differ") + + @property + def channels(self) -> int: + return int(self.gamma.shape[0]) + + @property + def scale(self) -> np.ndarray: + """``gamma / sqrt(var + eps)`` (float64).""" + return self.gamma / np.sqrt(self.var + self.eps) + + @property + def shift(self) -> np.ndarray: + """``beta - mean * scale`` (float64): ``bn(x) == x * scale + shift``.""" + return self.beta - self.mean * self.scale + + @classmethod + def from_state_dict(cls, sd: Mapping[str, Any], prefix: str, eps: float = 1e-5) -> "BatchNorm": + """torch naming: ``.weight``, ``.bias``, ``.running_mean``, ``.running_var``.""" + p = prefix.rstrip(".") + "." if prefix else "" + return cls(np.asarray(sd[p + "weight"]), np.asarray(sd[p + "bias"]), np.asarray(sd[p + "running_mean"]), + np.asarray(sd[p + "running_var"]), eps) + + def apply(self, x: np.ndarray, axis: int = 1) -> np.ndarray: + """Reference application in float64 (``axis`` = channel axis), for tests.""" + shape = [1] * np.ndim(x) + shape[axis] = -1 + return np.asarray(x, np.float64) * self.scale.reshape(shape) + self.shift.reshape(shape) + + +def _finish(w: np.ndarray, b: np.ndarray, dtype: Optional[Any]) -> Tuple[np.ndarray, np.ndarray]: + if dtype is None: + return w, b + return w.astype(dtype), b.astype(dtype) + + +def fold_bn(weight: np.ndarray, bias: Optional[np.ndarray], bn: BatchNorm, *, axis: int = 0, + dtype: Optional[Any] = np.float32) -> Tuple[np.ndarray, np.ndarray]: + """Fold ``bn`` (applied to the layer's output) into ``weight`` / ``bias``: ``W' = W * s`` along the output axis + ``axis`` and ``b' = (b - mean) * s + beta``, all in float64, one final rounding to ``dtype``.""" + w = np.asarray(weight, np.float64) + if w.shape[axis] != bn.channels: + raise ValueError(f"weight axis {axis} has {w.shape[axis]} channels, BatchNorm has {bn.channels}") + shape = [1] * w.ndim + shape[axis] = -1 + s = bn.scale + b = np.zeros(bn.channels, np.float64) if bias is None else np.asarray(bias, np.float64).reshape(-1) + return _finish(w * s.reshape(shape), (b - bn.mean) * s + bn.beta, dtype) + + +def fold_bn_conv(weight: np.ndarray, bias: Optional[np.ndarray], bn: BatchNorm, *, + dtype: Optional[Any] = np.float32) -> Tuple[np.ndarray, np.ndarray]: + """Conv1d/2d/3d weight ``[Cout, Cin/groups, k...]`` followed by BN (any ``groups``).""" + return fold_bn(weight, bias, bn, axis=0, dtype=dtype) + + +def fold_bn_linear(weight: np.ndarray, bias: Optional[np.ndarray], bn: BatchNorm, *, layout: str = "out_in", + dtype: Optional[Any] = np.float32) -> Tuple[np.ndarray, np.ndarray]: + """Linear / Gemm / MatMul followed by BN1d. ``layout="out_in"``: torch ``Linear`` and ONNX Gemm with + ``transB=1`` (``[out, in]``); ``"in_out"``: ONNX MatMul / Gemm ``transB=0`` (``[in, out]``).""" + if layout not in ("out_in", "in_out"): + raise ValueError("layout must be 'out_in' or 'in_out'") + return fold_bn(weight, bias, bn, axis=0 if layout == "out_in" else -1, dtype=dtype) + + +def fold_bn_conv_transpose(weight: np.ndarray, bias: Optional[np.ndarray], bn: BatchNorm, *, groups: int = 1, + dtype: Optional[Any] = np.float32) -> Tuple[np.ndarray, np.ndarray]: + """ConvTranspose weight ``[Cin, Cout/groups, k...]`` followed by BN: output channel of ``W[i, j]`` is + ``(i // (Cin/groups)) * (Cout/groups) + j``.""" + w = np.asarray(weight, np.float64) + cin, cout_g = w.shape[0], w.shape[1] + if cin % groups: + raise ValueError(f"Cin={cin} is not divisible by groups={groups}") + if cout_g * groups != bn.channels: + raise ValueError(f"ConvTranspose has {cout_g * groups} output channels, BatchNorm has {bn.channels}") + out_idx = (np.arange(cin)[:, None] // (cin // groups)) * cout_g + np.arange(cout_g)[None, :] + s = bn.scale[out_idx].reshape((cin, cout_g) + (1,) * (w.ndim - 2)) + b = np.zeros(bn.channels, np.float64) if bias is None else np.asarray(bias, np.float64).reshape(-1) + return _finish(w * s, (b - bn.mean) * bn.scale + bn.beta, dtype) + + +# ----------------------------------------------------------------------------------------------- ONNX + +@dataclass(frozen=True) +class OnnxNode: + """A graph node: name, op type, input / output tensor names and decoded attributes.""" + + name: str + op_type: str + inputs: Tuple[str, ...] + outputs: Tuple[str, ...] + attrs: Dict[str, Any] = field(default_factory=dict) + index: int = 0 + + +@dataclass(frozen=True) +class ConvParams: + """Weights and attributes of a Conv / ConvTranspose node. ``pads`` is the explicit attribute (zeros when + absent); with ``auto_pad`` ``SAME_UPPER`` / ``SAME_LOWER`` the real padding depends on the input size and must + be derived from it (PyTorch exports always write explicit pads and ``NOTSET``).""" + + weight: np.ndarray + bias: Optional[np.ndarray] + strides: Tuple[int, ...] + pads: Tuple[int, ...] + dilations: Tuple[int, ...] + group: int + kernel_shape: Tuple[int, ...] + output_padding: Tuple[int, ...] = () + auto_pad: str = "NOTSET" + output_shape: Tuple[int, ...] = () + + +@dataclass(frozen=True) +class GemmParams: + """Weights and attributes of a Gemm node (``weight`` exactly as stored; see ``trans_b``).""" + + weight: np.ndarray + bias: Optional[np.ndarray] + trans_a: bool + trans_b: bool + alpha: float + beta: float + + +def _attr_value(attr) -> Any: + from onnx import helper + + value = helper.get_attribute_value(attr) + if isinstance(value, bytes): + return value.decode("utf-8", "replace") + if isinstance(value, list) and value and isinstance(value[0], bytes): + return [v.decode("utf-8", "replace") for v in value] + return value + + +class OnnxWeights: + """Initializers and Constant tensors of an ONNX file, addressable by tensor name or by consuming node. + + Example:: + + w = OnnxWeights("pts_backbone_neck_head_centerpoint.onnx") + conv = w.conv("/backbone/blocks.0/blocks.0.0/Conv") # ConvParams(weight, bias, strides, ...) + wf, bf = w.fold_conv_bn("/backbone/blocks.0/blocks.0.0/Conv") # conv + its BN consumer, fp64 fold + k = w.param("/dit/blocks.0/attn/MatMul", 1) # anonymous MatMul weight by slot + for node in w.nodes("Conv", "/backbone/*"): # graph order, glob on node names + print(node.name, w.conv(node.name).weight.shape) + """ + + def __init__(self, path: PathLike, *, load_external_data: bool = True): + import onnx + + self.path = Path(path) + model = onnx.load(str(self.path), load_external_data=False) + if load_external_data: + self._load_external(model) + self._sha256: Optional[str] = None + graph = model.graph + self._tensors: Dict[str, Any] = {t.name: t for t in graph.initializer} + self._cache: Dict[str, np.ndarray] = {} + self._nodes: Dict[str, OnnxNode] = {} + self._order: List[str] = [] + self._producer: Dict[str, str] = {} + self._consumers: Dict[str, List[str]] = {} + self._alias: Dict[str, str] = {} + for i, n in enumerate(graph.node): + name = n.name or f"{n.op_type}_{i}" + if name in self._nodes: + name = f"{name}#{i}" + node = OnnxNode(name, n.op_type, tuple(n.input), tuple(n.output), + {a.name: _attr_value(a) for a in n.attribute}, i) + self._nodes[name] = node + self._order.append(name) + for out in n.output: + self._producer[out] = name + for inp in n.input: + if inp: + self._consumers.setdefault(inp, []).append(name) + if n.op_type == "Constant" and n.output: + self._add_constant(n.output[0], n) + for name in self._order: # Identity of a constant tensor is that tensor + node = self._nodes[name] + if node.op_type == "Identity" and node.inputs and node.outputs: + self._alias[node.outputs[0]] = node.inputs[0] + self.input_names = tuple(i.name for i in graph.input if i.name not in self._tensors) + self.output_names = tuple(o.name for o in graph.output) + self.opset = {o.domain or "ai.onnx": int(o.version) for o in model.opset_import} + + def _load_external(self, model) -> None: + from onnx import TensorProto + from onnx import external_data_helper as ext + + base = self.path.parent.resolve() + for tensor in model.graph.initializer: + if tensor.data_location != TensorProto.EXTERNAL: + continue + location = {e.key: e.value for e in tensor.external_data}.get("location", "") + target = (base / location).resolve() + if base not in target.parents: + raise ValueError(f"external data of {tensor.name!r} points outside {base}: {location!r}") + ext.load_external_data_for_tensor(tensor, str(base)) + tensor.data_location = TensorProto.DEFAULT + del tensor.external_data[:] + + def _add_constant(self, output: str, node) -> None: + from onnx import numpy_helper + + for attr in node.attribute: + if attr.name == "value": + self._tensors[output] = attr.t + elif attr.name in ("value_float", "value_floats", "value_int", "value_ints"): + dt = np.float32 if "float" in attr.name else np.int64 + self._cache[output] = np.asarray(_attr_value(attr), dtype=dt) + self._tensors[output] = numpy_helper.from_array(self._cache[output], output) + + # ---- tensors --------------------------------------------------------------------------------- + @property + def sha256(self) -> str: + """sha256 of the ``.onnx`` file (computed on first use; a cache-key ingredient).""" + if self._sha256 is None: + self._sha256 = file_sha256(self.path) + return self._sha256 + + def _resolve(self, name: str) -> str: + seen = set() + while name in self._alias and name not in self._tensors: + if name in seen: + raise ValueError(f"Identity cycle at {name!r}") + seen.add(name) + name = self._alias[name] + return name + + def has(self, name: str) -> bool: + """True if ``name`` is an initializer / Constant output (or an Identity of one).""" + return self._resolve(name) in self._tensors + + def array(self, name: str) -> np.ndarray: + """The constant tensor ``name`` as numpy (cached; treat it as read-only).""" + from onnx import numpy_helper + + key = self._resolve(name) + if key not in self._tensors: + raise KeyError(f"{name!r} is not an initializer or Constant output of {self.path.name}") + if key not in self._cache: + self._cache[key] = numpy_helper.to_array(self._tensors[key]) + return self._cache[key] + + def initializer_names(self) -> List[str]: + return sorted(self._tensors) + + def state_dict(self) -> Dict[str, np.ndarray]: + """Every constant tensor by name (the export's names; prefer node addressing for stability).""" + return {name: self.array(name) for name in self._tensors} + + # ---- nodes ----------------------------------------------------------------------------------- + def node(self, name: str) -> OnnxNode: + try: + return self._nodes[name] + except KeyError: + close = [n for n in self._order if name in n][:5] + raise KeyError(f"no node {name!r} in {self.path.name}" + (f"; similar: {close}" if close else "")) from None + + def nodes(self, op_type: Optional[str] = None, pattern: Optional[str] = None, *, + regex: bool = False) -> List[OnnxNode]: + """Nodes in graph order, filtered by op type and a glob (or ``regex=True``) on the node name.""" + rx = re.compile(pattern) if (pattern and regex) else None + out = [] + for name in self._order: + node = self._nodes[name] + if op_type is not None and node.op_type != op_type: + continue + if pattern is not None and not (rx.search(name) if rx else fnmatch.fnmatchcase(name, pattern)): + continue + out.append(node) + return out + + def find_node(self, pattern: str, op_type: Optional[str] = None, *, regex: bool = False) -> OnnxNode: + """Exactly one node matching ``pattern`` (and ``op_type``), else ``KeyError``.""" + found = self.nodes(op_type, pattern, regex=regex) + if len(found) != 1: + raise KeyError(f"{len(found)} nodes match {pattern!r} (op_type={op_type}): {[n.name for n in found[:8]]}") + return found[0] + + def producer(self, tensor: str) -> Optional[OnnxNode]: + name = self._producer.get(tensor) + return self._nodes[name] if name else None + + def consumers(self, tensor: str) -> List[OnnxNode]: + """Nodes reading tensor ``tensor`` (directly; Identity nodes are listed as consumers).""" + return [self._nodes[n] for n in self._consumers.get(tensor, [])] + + def consumer_of(self, tensor: str, op_type: Optional[str] = None) -> OnnxNode: + """The single consumer of ``tensor`` (optionally of ``op_type``), else ``KeyError``.""" + found = [n for n in self.consumers(tensor) if op_type is None or n.op_type == op_type] + if len(found) != 1: + raise KeyError(f"{tensor!r} has {len(found)} consumers of type {op_type}: {[n.name for n in found]}") + return found[0] + + def param(self, node_name: str, index: int) -> np.ndarray: + """The constant feeding input slot ``index`` of node ``node_name``.""" + node = self.node(node_name) + if index >= len(node.inputs) or not node.inputs[index]: + raise KeyError(f"node {node_name!r} ({node.op_type}) has no input {index}") + name = node.inputs[index] + if not self.has(name): + raise KeyError(f"input {index} of {node_name!r} is {name!r}, a runtime tensor, not a constant") + return self.array(name) + + def params(self, node_name: str) -> Dict[int, np.ndarray]: + """``{slot: array}`` for every constant input of the node.""" + node = self.node(node_name) + return {i: self.array(t) for i, t in enumerate(node.inputs) if t and self.has(t)} + + def conv(self, node_name: str) -> ConvParams: + """Conv / ConvTranspose weights (+ bias) and attributes with ONNX defaults filled in.""" + node = self.node(node_name) + if node.op_type not in ("Conv", "ConvTranspose"): + raise ValueError(f"{node_name!r} is {node.op_type}, not Conv/ConvTranspose") + w = self.param(node_name, 1) + b = self.param(node_name, 2) if len(node.inputs) > 2 and node.inputs[2] else None + k = tuple(node.attrs.get("kernel_shape", w.shape[2:])) + nd = len(k) + attrs = node.attrs + return ConvParams(w, b, tuple(attrs.get("strides", (1,) * nd)), tuple(attrs.get("pads", (0,) * 2 * nd)), + tuple(attrs.get("dilations", (1,) * nd)), int(attrs.get("group", 1)), k, + tuple(attrs.get("output_padding", ())), str(attrs.get("auto_pad", "NOTSET")), + tuple(attrs.get("output_shape", ()))) + + def gemm(self, node_name: str) -> GemmParams: + node = self.node(node_name) + if node.op_type != "Gemm": + raise ValueError(f"{node_name!r} is {node.op_type}, not Gemm") + b = self.param(node_name, 2) if len(node.inputs) > 2 and node.inputs[2] else None + return GemmParams(self.param(node_name, 1), b, bool(node.attrs.get("transA", 0)), + bool(node.attrs.get("transB", 0)), float(node.attrs.get("alpha", 1.0)), + float(node.attrs.get("beta", 1.0))) + + def matmul_weight(self, node_name: str) -> np.ndarray: + """The constant operand of a MatMul (``[in, out]`` when it is the right operand).""" + node = self.node(node_name) + consts = [i for i, t in enumerate(node.inputs[:2]) if t and self.has(t)] + if len(consts) != 1: + raise ValueError(f"MatMul {node_name!r} has {len(consts)} constant operands") + return self.array(node.inputs[consts[0]]) + + def batchnorm(self, node_name: str) -> BatchNorm: + node = self.node(node_name) + if node.op_type != "BatchNormalization": + raise ValueError(f"{node_name!r} is {node.op_type}, not BatchNormalization") + return BatchNorm(self.param(node_name, 1), self.param(node_name, 2), self.param(node_name, 3), + self.param(node_name, 4), float(node.attrs.get("epsilon", 1e-5))) + + def fold_conv_bn(self, conv_node: str, bn_node: Optional[str] = None, *, + dtype: Optional[Any] = np.float32) -> Tuple[np.ndarray, np.ndarray]: + """Conv / ConvTranspose weights with the following BatchNormalization folded in (float64, one rounding). + ``bn_node`` defaults to the single BatchNormalization consuming the conv output.""" + conv = self.conv(conv_node) + if bn_node is None: + bn_node = self.consumer_of(self.node(conv_node).outputs[0], "BatchNormalization").name + bn = self.batchnorm(bn_node) + if self.node(conv_node).op_type == "ConvTranspose": + return fold_bn_conv_transpose(conv.weight, conv.bias, bn, groups=conv.group, dtype=dtype) + return fold_bn_conv(conv.weight, conv.bias, bn, dtype=dtype) + + def __repr__(self) -> str: + return f"OnnxWeights({self.path.name}: {len(self._nodes)} nodes, {len(self._tensors)} constants)" + + +# ------------------------------------------------------------------------------------- state dicts + +def _torch_to_numpy(t: Any) -> np.ndarray: + t = t.detach().cpu() + if str(t.dtype) == "torch.bfloat16": + t = t.float() + return t.numpy() + + +def load_safetensors(path: PathLike) -> Dict[str, np.ndarray]: + """All tensors of a ``.safetensors`` file as numpy (bf16 tensors are widened to float32 through torch).""" + from safetensors import safe_open + + out: Dict[str, np.ndarray] = {} + try: + with safe_open(str(path), framework="numpy") as f: + for k in f.keys(): + out[k] = f.get_tensor(k) + return out + except (TypeError, ValueError): # bf16 has no numpy dtype + out.clear() + with safe_open(str(path), framework="pt") as f: + for k in f.keys(): + out[k] = _torch_to_numpy(f.get_tensor(k)) + return out + + +_CHECKPOINT_KEYS = ("state_dict", "model", "model_state_dict", "module", "net", "params") + + +def load_torch_checkpoint(path: PathLike, *, key: Optional[str] = None) -> Dict[str, np.ndarray]: + """A ``.pth`` / ``.pt`` / ``.ckpt`` checkpoint loaded with ``torch.load(weights_only=True)`` (data only: no + pickled code runs) -> ``{name: numpy}``. ``key`` selects a nested dict; otherwise the first of + ``state_dict`` / ``model`` / ``model_state_dict`` / ``module`` / ``net`` / ``params`` that holds tensors.""" + import torch + + obj = torch.load(str(path), map_location="cpu", weights_only=True) + if key is not None: + obj = obj[key] + elif isinstance(obj, Mapping) and not any(hasattr(v, "detach") for v in obj.values()): + for k in _CHECKPOINT_KEYS: + if isinstance(obj.get(k), Mapping): + obj = obj[k] + break + if not isinstance(obj, Mapping): + raise ValueError(f"{path}: no tensor dict found (pass key=)") + return {str(k): _torch_to_numpy(v) for k, v in obj.items() if hasattr(v, "detach")} + + +def load_state_dict(path: PathLike, **kwargs: Any) -> "StateDict": + """``.safetensors`` / ``.pth`` / ``.pt`` / ``.ckpt`` / ``.npz`` -> :class:`StateDict` (by file suffix).""" + p = Path(path) + suffix = p.suffix.lower() + if suffix == ".safetensors": + tensors = load_safetensors(p) + elif suffix in (".pth", ".pt", ".ckpt", ".bin"): + tensors = load_torch_checkpoint(p, **kwargs) + elif suffix == ".npz": + with np.load(p, allow_pickle=False) as z: + tensors = {k: z[k] for k in z.files} + else: + raise ValueError(f"unsupported weights file {p.name}") + return StateDict(tensors) + + +class StateDict(Mapping): + """A read-only ``{name: numpy}`` view with prefix scoping: ``sd.sub("backbone.layer1.")["0.conv1.weight"]``.""" + + def __init__(self, tensors: Mapping[str, np.ndarray], prefix: str = ""): + self._tensors = tensors + self.prefix = prefix + + def __getitem__(self, name: str) -> np.ndarray: + try: + return self._tensors[self.prefix + name] + except KeyError: + raise KeyError(f"{self.prefix + name!r} not in the state dict") from None + + def __iter__(self) -> Iterator[str]: + n = len(self.prefix) + return (k[n:] for k in self._tensors if k.startswith(self.prefix)) + + def __len__(self) -> int: + return sum(1 for _ in self) + + def sub(self, prefix: str) -> "StateDict": + return StateDict(self._tensors, self.prefix + prefix) + + def strip(self, prefix: str) -> "StateDict": + """Drop a leading ``prefix`` (e.g. ``module.``) from every key that has it.""" + return StateDict({(k[len(prefix):] if k.startswith(prefix) else k): v for k, v in self._tensors.items()}, + self.prefix) + + def bn(self, name: str, eps: float = 1e-5) -> BatchNorm: + """BatchNorm ``.{weight,bias,running_mean,running_var}``.""" + return BatchNorm.from_state_dict(self, name, eps) + + +# ----------------------------------------------------------------------------------------- device cache + +def file_sha256(path: PathLike, chunk: int = 1 << 20) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(chunk), b""): + h.update(block) + return h.hexdigest() + + +def cache_root() -> Path: + """``$TT_CACHE_PATH`` (tt-model containers mount ``/tensor-cache`` there), else ``~/.cache/ttaw``.""" + env = os.environ.get("TT_CACHE_PATH") + return Path(env) if env else Path.home() / ".cache" / "ttaw" + + +_SAFE = re.compile(r"[^A-Za-z0-9_.-]+") + + +class WeightCache: + """Prepared device tensors cached on disk as ttnn ``.tensorbin`` files. + + ``namespace`` names the model (``"tt_centerpoint/base"``); ``source_digest`` identifies the source weights + (e.g. ``OnnxWeights.sha256``) so a new revision gets a fresh directory. ``version`` names the preparation + recipe and is part of the directory too: the cache outlives images (tt-model mounts the host's + ``~/.cache/tt-model//tensors`` at ``/tensor-cache``), so an entry built by older preparation code from the + same source weights would otherwise be served to newer code; bump it (e.g. the bundle ``__version__`` plus a + prep revision) whenever the code that builds the tensors changes. Each entry is keyed by name, dtype and layout; + a loaded entry whose dtype, layout or (with ``shape=``) logical shape differs from the request is rebuilt. + ``enabled=None`` reads ``TTAW_WEIGHT_CACHE`` once (``0`` disables: every call rebuilds).""" + + def __init__(self, namespace: str, source_digest: str = "", *, version: str = "", + root: Optional[PathLike] = None, enabled: Optional[bool] = None): + if enabled is None: + enabled = os.environ.get("TTAW_WEIGHT_CACHE", "1").strip() not in ("0", "false", "off", "no") + self.enabled = bool(enabled) + parts = [p for p in namespace.strip("/").split("/") if p] + if not parts or any(p in (".", "..") for p in parts): + raise ValueError(f"bad cache namespace {namespace!r}") + leaf = (source_digest or "nodigest")[:16] + (f"-{_SAFE.sub('_', str(version))}" if version else "") + self.version = str(version) + self.dir = Path(root) if root is not None else cache_root() + self.dir = self.dir.joinpath(*(_SAFE.sub("_", p) for p in parts), leaf) + self.hits = 0 + self.misses = 0 + + def path(self, key: str, dtype: Any, layout: Any) -> Path: + tag = f"{key}|{dtype}|{layout}" + short = hashlib.sha1(tag.encode()).hexdigest()[:8] + dname = getattr(dtype, "name", str(dtype)).lower() + lname = getattr(layout, "name", str(layout)).lower() + return self.dir / f"{_SAFE.sub('_', key)[:120]}.{dname}.{lname}.{short}.tensorbin" + + def get(self, key: str, make: Callable[[], Any], *, dtype: Any, layout: Any = None, device: Any = None, + memory_config: Any = None, shape: Optional[Tuple[int, ...]] = None): + """The cached host tensor for ``key`` (built with ``make()`` -> numpy / torch on a miss), moved to + ``device`` with ``memory_config`` when given. ``shape``: the expected logical shape (an entry of another + shape is rebuilt).""" + import ttnn + + from .tensors import to_host_tensor, ttnn_dtype + + dtype = ttnn_dtype(dtype) + layout = ttnn.TILE_LAYOUT if layout is None else layout + host = None + p = self.path(key, dtype, layout) + if self.enabled and p.is_file(): + try: + host = ttnn.load_tensor(p) + except Exception: # noqa: BLE001 -- unreadable / old format: rebuild below + host = None + if host is not None and (host.dtype != dtype or host.layout != layout + or (shape is not None and tuple(host.shape) != tuple(shape))): + host = None # an entry of another recipe: rebuild + if host is not None: + self.hits += 1 + if host is None: + self.misses += 1 + host = to_host_tensor(make(), dtype, layout, shape=shape) + if self.enabled: + p.parent.mkdir(parents=True, exist_ok=True) + tmp = p.with_name(f".{p.stem}.{os.getpid()}.tmp.tensorbin") + ttnn.dump_tensor(tmp, host) + os.replace(tmp, p) + if device is None: + return host + return ttnn.to_device(host, device, memory_config=memory_config or ttnn.DRAM_MEMORY_CONFIG) + + def clear(self) -> int: + """Delete this namespace/digest directory's entries; returns how many files were removed.""" + n = 0 + if self.dir.is_dir(): + for f in self.dir.glob("*.tensorbin"): + f.unlink() + n += 1 + return n diff --git a/examples/quickstart.py b/examples/quickstart.py new file mode 100644 index 0000000000000000000000000000000000000000..603f1ce1ba6b2265388324143dc357a4709d9c1c --- /dev/null +++ b/examples/quickstart.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""DepthPro2 quickstart (the Python API): depth of the shipped sample image, then of a short clip. + + python examples/quickstart.py [--size L] [--image photo.jpg] [--cpu] + +Needs ttnn (a tt-metal build with the patches in ../patches/, or the container image) and one p150; ``--cpu`` runs +the same pipeline on the float32 CPU reference instead (slow, no chip). The weights are downloaded from Apple's +repositories at the pinned commits (Apple Machine Learning Research Model License: research purposes only). +""" +import argparse +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "code")) + +from tt_depthpro2 import DepthPro2, load_sample # noqa: E402 + + +def main() -> None: + ap = argparse.ArgumentParser() + ap.add_argument("--size", default="L", help="S, B, L or H") + ap.add_argument("--image", default=None, help="an image file (default: the shipped sample)") + ap.add_argument("--cpu", action="store_true", help="the float32 CPU reference instead of the p150") + a = ap.parse_args() + image = a.image or load_sample() + with DepthPro2.from_pretrained(a.size, backend="cpu" if a.cpu else "tt") as model: + out = model.infer(image) + st = out.stats() + print(f"{model!r}\n{Path(image).name}: {out.input_size[1]}x{out.input_size[0]} (bucket {out.bucket}, " + f"resized {out.resized}), f_px {out.focallength_px:.1f} ({out.focal_source}), depth median " + f"{st['median']:.2f} m (5-95 %: {st['p05']:.2f}-{st['p95']:.2f} m), {st['infinite_pixels']} sky pixels, " + f"{out.timing_ms['total']:.1f} ms") + png, meta = out.png16() # uint16 = round(depth_m * 1000); 0 = infinite (sky) + Path("depth16.png").write_bytes(png) + print("wrote depth16.png", meta["shape"], "saturated", meta["saturated_pixels"]) + # a video: frames of one size, buffered clips of `window` frames (here the image repeated) + frames = [image] * model.config.window + for frame in model.infer_video(frames): + if frame.frame_index in (0, len(frames) - 1): + print(f"video frame {frame.frame_index}: median {frame.stats()['median']:.2f} m") + + +if __name__ == "__main__": + main() diff --git a/image/blobs/sha256/019c993236fff2503e7919f178371e28a8d151d36ec72982bd75e79b5d61d5af b/image/blobs/sha256/019c993236fff2503e7919f178371e28a8d151d36ec72982bd75e79b5d61d5af new file mode 100644 index 0000000000000000000000000000000000000000..57c2d105e150c6e39a00db127e8a67666be749b7 --- /dev/null +++ b/image/blobs/sha256/019c993236fff2503e7919f178371e28a8d151d36ec72982bd75e79b5d61d5af @@ -0,0 +1,26 @@ +{ + "schemaVersion": 2, + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "artifactType": "application/vnd.docker.attestation.manifest.v1+json", + "config": { + "mediaType": "application/vnd.oci.empty.v1+json", + "digest": "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", + "size": 2, + "data": "e30=" + }, + "layers": [ + { + "mediaType": "application/vnd.in-toto+json", + "digest": "sha256:ee4869cd75114f2bcc8857f29640cab7a632f11a17a4d6dcfb8ab02dcccb4ae0", + "size": 1890, + "annotations": { + "in-toto.io/predicate-type": "https://slsa.dev/provenance/v1" + } + } + ], + "subject": { + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "digest": "sha256:0ee4564ba810e29d04812b4384a625bd8ae704d13e375f9c34c8d9d49039ff65", + "size": 4686 + } +} \ No newline at end of file diff --git a/image/blobs/sha256/0ee4564ba810e29d04812b4384a625bd8ae704d13e375f9c34c8d9d49039ff65 b/image/blobs/sha256/0ee4564ba810e29d04812b4384a625bd8ae704d13e375f9c34c8d9d49039ff65 new file mode 100644 index 0000000000000000000000000000000000000000..ac1fbfa8bb4d44287bd0f115898f5c6386d3c54b --- /dev/null +++ b/image/blobs/sha256/0ee4564ba810e29d04812b4384a625bd8ae704d13e375f9c34c8d9d49039ff65 @@ -0,0 +1,126 @@ +{ + "schemaVersion": 2, + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "config": { + "mediaType": "application/vnd.oci.image.config.v1+json", + "digest": "sha256:34020e6601d2b3b40db6cdfec30536e8a7b15b6b0c9612cd2fa29f21a7eee863", + "size": 14813 + }, + "layers": [ + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:ba082564e6605eeb2e1abc91a762985d2e8afea393433de08e798c1eee36d028", + "size": 30069815 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:671912666b1102907184fdf4478ef31010aaa5d3e790c872ed63a6f305af1674", + "size": 69477905 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:fdd5150ca1a0c2c722f552dda7ed3deaaa9289294931aca6825aed95c2ce4760", + "size": 4400 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:d43baab0c30010379faae769137459154234a3db3176feafda3ba268ba069d0f", + "size": 30938306 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:a90d913a3b293654e45a902690e86ee0a9cbee6dac59ccc9b8f5b6dcf70acfa0", + "size": 153119814 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:b5d78d46efec8b21102fcabc61b536b7c710fa075c56cc5573c7f25d000b2958", + "size": 65830751 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:5b016d79bb0d0f231feb56432bca597d22372330cae9fcbd57b66a767a0e0bde", + "size": 281699702 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:6b84c4b1e198fcf5606226d8bcbcb2bee61c8c2d7e45e4a24ebb077d51e7dbb9", + "size": 115 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:e5758dccd78c32a99fa2ad6fede7dcdc9a010195d5b2e52fdf578ad053a5efe1", + "size": 139083852 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:8ea3df7e57eca539aaef3886da4416edc8049442de5819442ff93435714efda2", + "size": 41057568 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:1431ca2d06bf0e3d6b058e48861af84ab9e0a76124a34cfc8668fbc33128cf31", + "size": 41057371 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:b2c200cde9649039e625dcd0b97cb038730866e1eea1f36fa1ade18f52890b37", + "size": 63874318 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:bd2a1526ee7e957e7890edc94a56b8d87c4106f128c96d3dfc5dbe5c6ca324d4", + "size": 13065803 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:26978a700289f033dd9238f908fb9bde859d9bf209a916db1a441ef7f08bbbcd", + "size": 1950905 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:8e640e05879de6ee1f5a3a511bd4907cc6fa5811d23ec76da3f9a4f7aec55599", + "size": 6888 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:fed26da465205879ddefd477dede4d90fccc48b762849d028c45f589ea4bf6f4", + "size": 801689 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:4f4fb700ef54461cfa02571ae0db9a0dc1e0cdb5577484a6d75e68dc38e8acc1", + "size": 32 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:a78d4158910533ecef000d98be19cc62db3ace7841507634f52935afcdb587ad", + "size": 1079 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:8dbb9dc6159f3f43fbb2af7bbc5ee536597279b22e23412ee49b4fb346a8f6ae", + "size": 1330 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:4f4fb700ef54461cfa02571ae0db9a0dc1e0cdb5577484a6d75e68dc38e8acc1", + "size": 32 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:599e044f5d508c6d7465d5c227174c066871016ed5afbea49f73a5b588c68a63", + "size": 2805 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:a0f9120f8473031e9c31209f61fc7dd3ab859a2dfb3001d7dfd8b5996df48b72", + "size": 226850 + }, + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "digest": "sha256:d068284065b9a015a2304692ae9ecfb3eb7886643b8dc12dd2d1123c1688a40f", + "size": 4041 + } + ] +} \ No newline at end of file diff --git a/image/blobs/sha256/1431ca2d06bf0e3d6b058e48861af84ab9e0a76124a34cfc8668fbc33128cf31 b/image/blobs/sha256/1431ca2d06bf0e3d6b058e48861af84ab9e0a76124a34cfc8668fbc33128cf31 new file mode 100644 index 0000000000000000000000000000000000000000..add35cb318b83b0b1f546d3e6a643fd10cac0dbd --- /dev/null +++ b/image/blobs/sha256/1431ca2d06bf0e3d6b058e48861af84ab9e0a76124a34cfc8668fbc33128cf31 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1431ca2d06bf0e3d6b058e48861af84ab9e0a76124a34cfc8668fbc33128cf31 +size 41057371 diff --git a/image/blobs/sha256/26978a700289f033dd9238f908fb9bde859d9bf209a916db1a441ef7f08bbbcd b/image/blobs/sha256/26978a700289f033dd9238f908fb9bde859d9bf209a916db1a441ef7f08bbbcd new file mode 100644 index 0000000000000000000000000000000000000000..a6881d3531d5e368120ec9951521a9455fe4785b --- /dev/null +++ b/image/blobs/sha256/26978a700289f033dd9238f908fb9bde859d9bf209a916db1a441ef7f08bbbcd @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26978a700289f033dd9238f908fb9bde859d9bf209a916db1a441ef7f08bbbcd +size 1950905 diff --git a/image/blobs/sha256/34020e6601d2b3b40db6cdfec30536e8a7b15b6b0c9612cd2fa29f21a7eee863 b/image/blobs/sha256/34020e6601d2b3b40db6cdfec30536e8a7b15b6b0c9612cd2fa29f21a7eee863 new file mode 100644 index 0000000000000000000000000000000000000000..5ad05c73702e82705d4cd628e205d75914467bc9 --- /dev/null +++ b/image/blobs/sha256/34020e6601d2b3b40db6cdfec30536e8a7b15b6b0c9612cd2fa29f21a7eee863 @@ -0,0 +1 @@ +{"architecture":"amd64","config":{"User":"tt","Env":["PATH=/opt/tt-venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","VENV=/opt/tt-venv","VIRTUAL_ENV=/opt/tt-venv","TT_METAL_RUNTIME_ROOT=/opt/tt-metal","TT_METAL_HOME=/opt/tt-metal","PYTHONPATH=/opt/tt-metal","LD_LIBRARY_PATH=/opt/tt-metal/build/lib:/opt/openmpi-v5.0.7-ulfm/lib","EXTRA_MODELS_DIR=","TT_VLLM_BUILTIN_MODELS=","TT_MODEL_KIND=tt-dit-server","HF_HOME=/hf","TT_METAL_CACHE=/cache","HOME=/home/tt","USER=tt","LOGNAME=tt"],"Entrypoint":["/usr/local/bin/entrypoint.sh"],"Cmd":["/usr/local/bin/serve-default.sh"],"WorkingDir":"/home/tt/work","Labels":{"org.opencontainers.image.revision":"44d66500520fda9f2c7060c0f6b41ec48f7ab37e","org.opencontainers.image.version":"22.04","org.tenstorrent.tt-model":"depthpro2","org.tenstorrent.tt-model.arch":"blackhole","org.tenstorrent.tt-model.kind":"tt-dit-server","org.tenstorrent.tt-model.plugin":"","org.tenstorrent.tt-model.profiles":"s,b,l,h","org.tenstorrent.tt-model.repo":"changh95/DepthPro2","org.tenstorrent.tt-model.tt-metal":"v0.80.0-dev20261006-78-g44d6650052-dirty","org.tenstorrent.tt-model.weights":"apple/DepthPro2-focal"},"ArgsEscaped":true},"created":"2026-11-29T04:47:38.870680808Z","history":[{"created":"2026-11-17T09:18:24.816545885Z","created_by":"/bin/sh -c #(nop) ARG RELEASE","empty_layer":true},{"created":"2026-11-17T09:18:24.854129732Z","created_by":"/bin/sh -c #(nop) ARG LAUNCHPAD_BUILD_ARCH","empty_layer":true},{"created":"2026-11-17T09:18:24.882016179Z","created_by":"/bin/sh -c #(nop) LABEL org.opencontainers.image.version=22.04","empty_layer":true},{"created":"2026-11-17T09:18:27.119966628Z","created_by":"/bin/sh -c #(nop) ADD file:577abcbf057cdd5d520b6dbfa56d772c9fb1fa3dd63cb6db8942d63dfc9d902b in / "},{"created":"2026-11-17T09:18:27.522347875Z","created_by":"/bin/sh -c #(nop) CMD [\"/bin/bash\"]","empty_layer":true},{"created":"2026-11-28T16:42:42.875638712Z","created_by":"ARG OMPI_DIR=/opt/openmpi-v5.0.7-ulfm","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-28T16:42:42.875638712Z","created_by":"ARG EXTRA_MODELS_DIR=","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-28T16:42:42.875638712Z","created_by":"ARG TT_MODEL_KIND","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-28T16:42:42.875638712Z","created_by":"ARG MODEL_NAME","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-28T16:42:42.875638712Z","created_by":"ARG MODEL_REPO","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-28T16:42:42.875638712Z","created_by":"ARG MODEL_WEIGHTS","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-28T16:42:42.875638712Z","created_by":"ARG MODEL_ARCH","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-28T16:42:42.875638712Z","created_by":"ARG MODEL_PROFILES","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-28T16:42:42.875638712Z","created_by":"ARG MODEL_TT_METAL_SHA","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-28T16:42:42.875638712Z","created_by":"ARG MODEL_TT_METAL_DESCRIBE","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-28T16:42:42.875638712Z","created_by":"ARG MODEL_PLUGIN_SHA","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-28T16:42:42.875638712Z","created_by":"RUN |11 OMPI_DIR=/opt/openmpi-v5.0.7-ulfm EXTRA_MODELS_DIR= TT_MODEL_KIND=tt-dit-server MODEL_NAME=depthpro2 MODEL_REPO=changh95/DepthPro2 MODEL_WEIGHTS=apple/DepthPro2-focal MODEL_ARCH=blackhole MODEL_PROFILES=s,b,l,h MODEL_TT_METAL_SHA=44d66500520fda9f2c7060c0f6b41ec48f7ab37e MODEL_TT_METAL_DESCRIBE=v0.80.0-dev20261006-78-g44d6650052-dirty MODEL_PLUGIN_SHA= /bin/sh -c apt-get update \u0026\u0026 apt-get install -y --no-install-recommends libhwloc15 libnuma1 libatomic1 libudev1 libcap2 zlib1g libmpc3 libmpfr6 libgmp10 libzstd1 libevent-core-2.1-7 libevent-pthreads-2.1-7 libgl1 libsndfile1 ca-certificates \u0026\u0026 apt-get clean \u0026\u0026 rm -rf /var/lib/apt/lists/* # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-28T16:42:45.530315653Z","created_by":"RUN |11 OMPI_DIR=/opt/openmpi-v5.0.7-ulfm EXTRA_MODELS_DIR= TT_MODEL_KIND=tt-dit-server MODEL_NAME=depthpro2 MODEL_REPO=changh95/DepthPro2 MODEL_WEIGHTS=apple/DepthPro2-focal MODEL_ARCH=blackhole MODEL_PROFILES=s,b,l,h MODEL_TT_METAL_SHA=44d66500520fda9f2c7060c0f6b41ec48f7ab37e MODEL_TT_METAL_DESCRIBE=v0.80.0-dev20261006-78-g44d6650052-dirty MODEL_PLUGIN_SHA= /bin/sh -c existing=\"$(getent passwd 1000 | cut -d: -f1)\" \u0026\u0026 if [ -n \"$existing\" ]; then userdel -r \"$existing\" 2\u003e/dev/null || userdel \"$existing\"; fi \u0026\u0026 useradd --uid 1000 --create-home --home-dir /home/tt --shell /bin/bash tt \u0026\u0026 mkdir -p /home/tt/work/logs /cache /opt/tt-metal \u0026\u0026 chown -R tt:tt /home/tt /cache /opt/tt-metal \u0026\u0026 chmod 1777 /home/tt /home/tt/work /home/tt/work/logs /cache # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-28T17:33:04.345303757Z","created_by":"COPY /opt/openmpi-v5.0.7-ulfm /opt/openmpi-v5.0.7-ulfm # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-28T17:33:06.736780269Z","created_by":"COPY /opt/tenstorrent /opt/tenstorrent # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:03:58.415192544Z","created_by":"COPY /usr/local/share/uv /usr/local/share/uv # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:46:52.727342635Z","created_by":"COPY /opt/tt-venv /opt/tt-venv # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:46:52.97009031Z","created_by":"COPY /opt/vllm /opt/vllm # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:46:55.62060252Z","created_by":"COPY --chown=tt:tt /opt/tt-metal/runtime /opt/tt-metal/runtime # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:46:56.411762076Z","created_by":"COPY --chown=tt:tt /opt/tt-metal/build_Release /opt/tt-metal/build_Release # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:46:57.159555653Z","created_by":"COPY --chown=tt:tt /opt/tt-metal/build /opt/tt-metal/build # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:46:59.51668971Z","created_by":"COPY --chown=tt:tt /opt/tt-metal/tt_metal /opt/tt-metal/tt_metal # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:47:01.253235215Z","created_by":"COPY --chown=tt:tt /opt/tt-metal/ttnn /opt/tt-metal/ttnn # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:47:01.494932374Z","created_by":"COPY --chown=tt:tt /opt/tt-metal/tools /opt/tt-metal/tools # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:47:01.538078264Z","created_by":"COPY --chown=tt:tt /opt/tt-metal/setup.py /opt/tt-metal/pyproject.toml /opt/tt-metal/ # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:47:01.605121831Z","created_by":"COPY --chown=tt:tt code/ /opt/tt-metal/ # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:47:02.129615414Z","created_by":"RUN |11 OMPI_DIR=/opt/openmpi-v5.0.7-ulfm EXTRA_MODELS_DIR= TT_MODEL_KIND=tt-dit-server MODEL_NAME=depthpro2 MODEL_REPO=changh95/DepthPro2 MODEL_WEIGHTS=apple/DepthPro2-focal MODEL_ARCH=blackhole MODEL_PROFILES=s,b,l,h MODEL_TT_METAL_SHA=44d66500520fda9f2c7060c0f6b41ec48f7ab37e MODEL_TT_METAL_DESCRIBE=v0.80.0-dev20261006-78-g44d6650052-dirty MODEL_PLUGIN_SHA= /bin/sh -c find /opt/tt-metal \\( -type f -o -type d \\) \\( ! -perm -o+r -o \\( -type d ! -perm -o+x \\) \\) -exec chmod a+rX {} + # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:47:02.15726282Z","created_by":"COPY --chmod=0755 entrypoint.sh /usr/local/bin/entrypoint.sh # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"COPY --chmod=0755 serve-default.sh /usr/local/bin/serve-default.sh # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV VENV=/opt/tt-venv","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV VIRTUAL_ENV=/opt/tt-venv","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV PATH=/opt/tt-venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV TT_METAL_RUNTIME_ROOT=/opt/tt-metal","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV TT_METAL_HOME=/opt/tt-metal","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV PYTHONPATH=/opt/tt-metal","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV LD_LIBRARY_PATH=/opt/tt-metal/build/lib:/opt/openmpi-v5.0.7-ulfm/lib","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV EXTRA_MODELS_DIR=","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ARG TT_VLLM_BUILTIN_MODELS=","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV TT_VLLM_BUILTIN_MODELS=","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV TT_MODEL_KIND=tt-dit-server","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV HF_HOME=/hf","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV TT_METAL_CACHE=/cache","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV HOME=/home/tt","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV USER=tt","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"ENV LOGNAME=tt","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.181108308Z","created_by":"USER tt","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:02.206375101Z","created_by":"WORKDIR /home/tt/work","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:47:02.228889563Z","created_by":"COPY --chmod=0755 verify.sh /ctx/verify.sh # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:47:38.638260761Z","created_by":"RUN |12 OMPI_DIR=/opt/openmpi-v5.0.7-ulfm EXTRA_MODELS_DIR= TT_MODEL_KIND=tt-dit-server MODEL_NAME=depthpro2 MODEL_REPO=changh95/DepthPro2 MODEL_WEIGHTS=apple/DepthPro2-focal MODEL_ARCH=blackhole MODEL_PROFILES=s,b,l,h MODEL_TT_METAL_SHA=44d66500520fda9f2c7060c0f6b41ec48f7ab37e MODEL_TT_METAL_DESCRIBE=v0.80.0-dev20261006-78-g44d6650052-dirty MODEL_PLUGIN_SHA= TT_VLLM_BUILTIN_MODELS= /bin/sh -c bash /ctx/verify.sh # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:47:38.638260761Z","created_by":"USER root","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:38.870680808Z","created_by":"RUN |12 OMPI_DIR=/opt/openmpi-v5.0.7-ulfm EXTRA_MODELS_DIR= TT_MODEL_KIND=tt-dit-server MODEL_NAME=depthpro2 MODEL_REPO=changh95/DepthPro2 MODEL_WEIGHTS=apple/DepthPro2-focal MODEL_ARCH=blackhole MODEL_PROFILES=s,b,l,h MODEL_TT_METAL_SHA=44d66500520fda9f2c7060c0f6b41ec48f7ab37e MODEL_TT_METAL_DESCRIBE=v0.80.0-dev20261006-78-g44d6650052-dirty MODEL_PLUGIN_SHA= TT_VLLM_BUILTIN_MODELS= /bin/sh -c chmod -R a+rwX /home/tt # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-11-29T04:47:38.870680808Z","created_by":"USER tt","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:38.870680808Z","created_by":"LABEL org.tenstorrent.tt-model=depthpro2 org.tenstorrent.tt-model.repo=changh95/DepthPro2 org.tenstorrent.tt-model.weights=apple/DepthPro2-focal org.tenstorrent.tt-model.arch=blackhole org.tenstorrent.tt-model.kind=tt-dit-server org.tenstorrent.tt-model.profiles=s,b,l,h org.opencontainers.image.revision=44d66500520fda9f2c7060c0f6b41ec48f7ab37e org.tenstorrent.tt-model.tt-metal=v0.80.0-dev20261006-78-g44d6650052-dirty org.tenstorrent.tt-model.plugin=","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:38.870680808Z","created_by":"ENTRYPOINT [\"/usr/local/bin/entrypoint.sh\"]","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-11-29T04:47:38.870680808Z","created_by":"CMD [\"/usr/local/bin/serve-default.sh\"]","comment":"buildkit.dockerfile.v0","empty_layer":true}],"os":"linux","rootfs":{"type":"layers","diff_ids":["sha256:af272fa34b9eaf77b9456d49daa4d157829b4e27b91a79d1fe5602a1556635ad","sha256:8be42d4b03bc877f158ffd738dbac17e4fa8285b19cf74169c879f5c512a8b71","sha256:22a3ab3fa9eb410f82963b0a29e0ccaab2fd7d1dff10ed16225b57170800648a","sha256:fb97a966331b85e18e7da95840b6cbad01fe8da3b4ee57008db90c4ceefadc60","sha256:f6f59c740d38f0240384e0389b9eb70a0ff1c291067da2551629d026caf317bb","sha256:b5243dd282602a10edfac49ffa271ffe1958c0de5a1ad0939ea7916d2641bb2b","sha256:01b554b2eaf598c7894c94dc9d32f9aa20620af96b61cb41855e5adcfd80d611","sha256:08ce13856815b7a648a10c4857f9d9ab854193eb439ee42998163104c611e480","sha256:e3387cb5295f94f7605f4f0ea57528f1fb7963cea7f29d808f2508670137b7b3","sha256:03c36d4a647124c720352b35ee5ac6b54b54894824a6939b67264e2130c67896","sha256:f83f0bd8e1a8437031852372b99863f72db792ab5e1ad701c68651922c4a4862","sha256:83864dc68411162d474a91d149ca2177ee56141c677278acd5e7e721cee33c4c","sha256:0f3b4df390ced8047d3500b2228d3b255c9b50bb5663c3019c19a679c503afac","sha256:a897859c7d9035ac032a499635bc36609d707a745003c124799fb27fd70dea45","sha256:b56609537a1465ccf8d184dc6f90a6cd2277118375cac6f8bb3d26e443aaa798","sha256:5263d123111619e405b31b220db53237c305b92e566fefb3bf46dbf377dd0606","sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef","sha256:da770958d95dcef917a2e5fc5a6153add72d2c2ecafe68098227691d3caf696b","sha256:e1007bec59c6206b0175bf8b72a2b0977b05b65e25bb0cb9368ddaf09be670a8","sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef","sha256:c563f3f8684d69cbe857a2d8a53ac2dc747f647c3bd6fd99488e7c6c1ef2fbe5","sha256:770185739466f487869cadf05c9089669df7e5dbd19ab3d427c9368a2a867e34","sha256:93143bb51f9dece859aa55973e31c4274baf5786177a74bb7ca5d6c554c06675"]}} \ No newline at end of file diff --git a/image/blobs/sha256/44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a b/image/blobs/sha256/44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a new file mode 100644 index 0000000000000000000000000000000000000000..9e26dfeeb6e641a33dae4961196235bdb965b21b --- /dev/null +++ b/image/blobs/sha256/44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/image/blobs/sha256/4f4fb700ef54461cfa02571ae0db9a0dc1e0cdb5577484a6d75e68dc38e8acc1 b/image/blobs/sha256/4f4fb700ef54461cfa02571ae0db9a0dc1e0cdb5577484a6d75e68dc38e8acc1 new file mode 100644 index 0000000000000000000000000000000000000000..8de868223f695a02a4da72b1e79a6545868048c5 Binary files /dev/null and b/image/blobs/sha256/4f4fb700ef54461cfa02571ae0db9a0dc1e0cdb5577484a6d75e68dc38e8acc1 differ diff --git a/image/blobs/sha256/599e044f5d508c6d7465d5c227174c066871016ed5afbea49f73a5b588c68a63 b/image/blobs/sha256/599e044f5d508c6d7465d5c227174c066871016ed5afbea49f73a5b588c68a63 new file mode 100644 index 0000000000000000000000000000000000000000..f750bffaa5d28ef7cdb8555579bc71e94b6408b7 Binary files /dev/null and b/image/blobs/sha256/599e044f5d508c6d7465d5c227174c066871016ed5afbea49f73a5b588c68a63 differ diff --git a/image/blobs/sha256/5b016d79bb0d0f231feb56432bca597d22372330cae9fcbd57b66a767a0e0bde b/image/blobs/sha256/5b016d79bb0d0f231feb56432bca597d22372330cae9fcbd57b66a767a0e0bde new file mode 100644 index 0000000000000000000000000000000000000000..c9fb083f53a361cbc2451dc60d51a8e2fc519346 --- /dev/null +++ b/image/blobs/sha256/5b016d79bb0d0f231feb56432bca597d22372330cae9fcbd57b66a767a0e0bde @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b016d79bb0d0f231feb56432bca597d22372330cae9fcbd57b66a767a0e0bde +size 281699702 diff --git a/image/blobs/sha256/671912666b1102907184fdf4478ef31010aaa5d3e790c872ed63a6f305af1674 b/image/blobs/sha256/671912666b1102907184fdf4478ef31010aaa5d3e790c872ed63a6f305af1674 new file mode 100644 index 0000000000000000000000000000000000000000..c9d0ed71a03b957a05829a7966936708ce403139 --- /dev/null +++ b/image/blobs/sha256/671912666b1102907184fdf4478ef31010aaa5d3e790c872ed63a6f305af1674 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:671912666b1102907184fdf4478ef31010aaa5d3e790c872ed63a6f305af1674 +size 69477905 diff --git a/image/blobs/sha256/6b84c4b1e198fcf5606226d8bcbcb2bee61c8c2d7e45e4a24ebb077d51e7dbb9 b/image/blobs/sha256/6b84c4b1e198fcf5606226d8bcbcb2bee61c8c2d7e45e4a24ebb077d51e7dbb9 new file mode 100644 index 0000000000000000000000000000000000000000..cc952e5e3ee35130c7d2e601546ba5bd701c0a8f Binary files /dev/null and b/image/blobs/sha256/6b84c4b1e198fcf5606226d8bcbcb2bee61c8c2d7e45e4a24ebb077d51e7dbb9 differ diff --git a/image/blobs/sha256/8405af31ce627ee3d18eb7e0bf0aa8c4d8c2e8625851e733d98a8bfdbc1cfeba b/image/blobs/sha256/8405af31ce627ee3d18eb7e0bf0aa8c4d8c2e8625851e733d98a8bfdbc1cfeba new file mode 100644 index 0000000000000000000000000000000000000000..97e94fca2645995f16504541b17e570287215de0 --- /dev/null +++ b/image/blobs/sha256/8405af31ce627ee3d18eb7e0bf0aa8c4d8c2e8625851e733d98a8bfdbc1cfeba @@ -0,0 +1,28 @@ +{ + "schemaVersion": 2, + "mediaType": "application/vnd.oci.image.index.v1+json", + "manifests": [ + { + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "digest": "sha256:0ee4564ba810e29d04812b4384a625bd8ae704d13e375f9c34c8d9d49039ff65", + "size": 4686, + "platform": { + "architecture": "amd64", + "os": "linux" + } + }, + { + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "digest": "sha256:019c993236fff2503e7919f178371e28a8d151d36ec72982bd75e79b5d61d5af", + "size": 837, + "annotations": { + "vnd.docker.reference.digest": "sha256:0ee4564ba810e29d04812b4384a625bd8ae704d13e375f9c34c8d9d49039ff65", + "vnd.docker.reference.type": "attestation-manifest" + }, + "platform": { + "architecture": "unknown", + "os": "unknown" + } + } + ] +} \ No newline at end of file diff --git a/image/blobs/sha256/8dbb9dc6159f3f43fbb2af7bbc5ee536597279b22e23412ee49b4fb346a8f6ae b/image/blobs/sha256/8dbb9dc6159f3f43fbb2af7bbc5ee536597279b22e23412ee49b4fb346a8f6ae new file mode 100644 index 0000000000000000000000000000000000000000..2d8cb02ecb29a5c6c0bc9bf0bfa3ea42975a83e9 Binary files /dev/null and b/image/blobs/sha256/8dbb9dc6159f3f43fbb2af7bbc5ee536597279b22e23412ee49b4fb346a8f6ae differ diff --git a/image/blobs/sha256/8e640e05879de6ee1f5a3a511bd4907cc6fa5811d23ec76da3f9a4f7aec55599 b/image/blobs/sha256/8e640e05879de6ee1f5a3a511bd4907cc6fa5811d23ec76da3f9a4f7aec55599 new file mode 100644 index 0000000000000000000000000000000000000000..5c2474d7b4f25bef7ed969546e43754adce06406 Binary files /dev/null and b/image/blobs/sha256/8e640e05879de6ee1f5a3a511bd4907cc6fa5811d23ec76da3f9a4f7aec55599 differ diff --git a/image/blobs/sha256/8ea3df7e57eca539aaef3886da4416edc8049442de5819442ff93435714efda2 b/image/blobs/sha256/8ea3df7e57eca539aaef3886da4416edc8049442de5819442ff93435714efda2 new file mode 100644 index 0000000000000000000000000000000000000000..cdd43d0542ddf516e3f746e36e7f182c77e5c33b --- /dev/null +++ b/image/blobs/sha256/8ea3df7e57eca539aaef3886da4416edc8049442de5819442ff93435714efda2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ea3df7e57eca539aaef3886da4416edc8049442de5819442ff93435714efda2 +size 41057568 diff --git a/image/blobs/sha256/a0f9120f8473031e9c31209f61fc7dd3ab859a2dfb3001d7dfd8b5996df48b72 b/image/blobs/sha256/a0f9120f8473031e9c31209f61fc7dd3ab859a2dfb3001d7dfd8b5996df48b72 new file mode 100644 index 0000000000000000000000000000000000000000..cca6c258e5e692e471f0d81d2711f0edc658e825 --- /dev/null +++ b/image/blobs/sha256/a0f9120f8473031e9c31209f61fc7dd3ab859a2dfb3001d7dfd8b5996df48b72 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0f9120f8473031e9c31209f61fc7dd3ab859a2dfb3001d7dfd8b5996df48b72 +size 226850 diff --git a/image/blobs/sha256/a78d4158910533ecef000d98be19cc62db3ace7841507634f52935afcdb587ad b/image/blobs/sha256/a78d4158910533ecef000d98be19cc62db3ace7841507634f52935afcdb587ad new file mode 100644 index 0000000000000000000000000000000000000000..fb89697c49bfe252896780315af153da8a0f25f9 Binary files /dev/null and b/image/blobs/sha256/a78d4158910533ecef000d98be19cc62db3ace7841507634f52935afcdb587ad differ diff --git a/image/blobs/sha256/a90d913a3b293654e45a902690e86ee0a9cbee6dac59ccc9b8f5b6dcf70acfa0 b/image/blobs/sha256/a90d913a3b293654e45a902690e86ee0a9cbee6dac59ccc9b8f5b6dcf70acfa0 new file mode 100644 index 0000000000000000000000000000000000000000..3d519e84e091ee1784693d65717e9b923f423e62 --- /dev/null +++ b/image/blobs/sha256/a90d913a3b293654e45a902690e86ee0a9cbee6dac59ccc9b8f5b6dcf70acfa0 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a90d913a3b293654e45a902690e86ee0a9cbee6dac59ccc9b8f5b6dcf70acfa0 +size 153119814 diff --git a/image/blobs/sha256/b2c200cde9649039e625dcd0b97cb038730866e1eea1f36fa1ade18f52890b37 b/image/blobs/sha256/b2c200cde9649039e625dcd0b97cb038730866e1eea1f36fa1ade18f52890b37 new file mode 100644 index 0000000000000000000000000000000000000000..87c1738c71cfd19fe74e7212c3aa42b52dd378e4 --- /dev/null +++ b/image/blobs/sha256/b2c200cde9649039e625dcd0b97cb038730866e1eea1f36fa1ade18f52890b37 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2c200cde9649039e625dcd0b97cb038730866e1eea1f36fa1ade18f52890b37 +size 63874318 diff --git a/image/blobs/sha256/b5d78d46efec8b21102fcabc61b536b7c710fa075c56cc5573c7f25d000b2958 b/image/blobs/sha256/b5d78d46efec8b21102fcabc61b536b7c710fa075c56cc5573c7f25d000b2958 new file mode 100644 index 0000000000000000000000000000000000000000..fe592a09ae8ff9ec0f018500322a5816460482f7 --- /dev/null +++ b/image/blobs/sha256/b5d78d46efec8b21102fcabc61b536b7c710fa075c56cc5573c7f25d000b2958 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5d78d46efec8b21102fcabc61b536b7c710fa075c56cc5573c7f25d000b2958 +size 65830751 diff --git a/image/blobs/sha256/ba082564e6605eeb2e1abc91a762985d2e8afea393433de08e798c1eee36d028 b/image/blobs/sha256/ba082564e6605eeb2e1abc91a762985d2e8afea393433de08e798c1eee36d028 new file mode 100644 index 0000000000000000000000000000000000000000..ce017d1bbd70a14d9eeeebae592b061b371ff932 --- /dev/null +++ b/image/blobs/sha256/ba082564e6605eeb2e1abc91a762985d2e8afea393433de08e798c1eee36d028 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba082564e6605eeb2e1abc91a762985d2e8afea393433de08e798c1eee36d028 +size 30069815 diff --git a/image/blobs/sha256/bd2a1526ee7e957e7890edc94a56b8d87c4106f128c96d3dfc5dbe5c6ca324d4 b/image/blobs/sha256/bd2a1526ee7e957e7890edc94a56b8d87c4106f128c96d3dfc5dbe5c6ca324d4 new file mode 100644 index 0000000000000000000000000000000000000000..bedcf087f65ea5855063604e402d959c770895e8 --- /dev/null +++ b/image/blobs/sha256/bd2a1526ee7e957e7890edc94a56b8d87c4106f128c96d3dfc5dbe5c6ca324d4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bd2a1526ee7e957e7890edc94a56b8d87c4106f128c96d3dfc5dbe5c6ca324d4 +size 13065803 diff --git a/image/blobs/sha256/d068284065b9a015a2304692ae9ecfb3eb7886643b8dc12dd2d1123c1688a40f b/image/blobs/sha256/d068284065b9a015a2304692ae9ecfb3eb7886643b8dc12dd2d1123c1688a40f new file mode 100644 index 0000000000000000000000000000000000000000..c6960195f2fa703bc59f9d8713a85cde6b6138c4 Binary files /dev/null and b/image/blobs/sha256/d068284065b9a015a2304692ae9ecfb3eb7886643b8dc12dd2d1123c1688a40f differ diff --git a/image/blobs/sha256/d43baab0c30010379faae769137459154234a3db3176feafda3ba268ba069d0f b/image/blobs/sha256/d43baab0c30010379faae769137459154234a3db3176feafda3ba268ba069d0f new file mode 100644 index 0000000000000000000000000000000000000000..e8a7cf78bb05df02db86654480dfa08e7bb0f029 --- /dev/null +++ b/image/blobs/sha256/d43baab0c30010379faae769137459154234a3db3176feafda3ba268ba069d0f @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d43baab0c30010379faae769137459154234a3db3176feafda3ba268ba069d0f +size 30938306 diff --git a/image/blobs/sha256/e5758dccd78c32a99fa2ad6fede7dcdc9a010195d5b2e52fdf578ad053a5efe1 b/image/blobs/sha256/e5758dccd78c32a99fa2ad6fede7dcdc9a010195d5b2e52fdf578ad053a5efe1 new file mode 100644 index 0000000000000000000000000000000000000000..e2ddcb5d9a19a644aa0ceb9f7bbf715fce122986 --- /dev/null +++ b/image/blobs/sha256/e5758dccd78c32a99fa2ad6fede7dcdc9a010195d5b2e52fdf578ad053a5efe1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5758dccd78c32a99fa2ad6fede7dcdc9a010195d5b2e52fdf578ad053a5efe1 +size 139083852 diff --git a/image/blobs/sha256/ee4869cd75114f2bcc8857f29640cab7a632f11a17a4d6dcfb8ab02dcccb4ae0 b/image/blobs/sha256/ee4869cd75114f2bcc8857f29640cab7a632f11a17a4d6dcfb8ab02dcccb4ae0 new file mode 100644 index 0000000000000000000000000000000000000000..5c6742279a38c874644a973e5aad5e9f5527282a --- /dev/null +++ b/image/blobs/sha256/ee4869cd75114f2bcc8857f29640cab7a632f11a17a4d6dcfb8ab02dcccb4ae0 @@ -0,0 +1 @@ +{"_type":"https://in-toto.io/Statement/v1","predicateType":"https://slsa.dev/provenance/v1","subject":[{"name":"pkg:docker/tt-model/depthpro2@build-44d665005?platform=linux%2Famd64","digest":{"sha256":"0ee4564ba810e29d04812b4384a625bd8ae704d13e375f9c34c8d9d49039ff65"}}],"predicate":{"buildDefinition":{"buildType":"https://github.com/moby/buildkit/blob/master/docs/attestations/slsa-definitions.md","resolvedDependencies":[{"uri":"pkg:docker/docker/dockerfile@1.7-labs","digest":{"sha256":"b99fecfe00268a8b556fad7d9c37ee25d716ae08a5d7320e6d51c4dd83246894"}},{"uri":"pkg:docker/ubuntu@22.04?platform=linux%2Famd64","digest":{"sha256":"b000e69a50ff940390233025e7a337fb8469b509e2334fa4d018ac30f3e18cdb"}},{"uri":"pkg:docker/ghcr.io/tenstorrent/tt-metal/tt-metalium/ubuntu-22.04-dev-amd64@latest?platform=linux%2Famd64","digest":{"sha256":"7f43e71c95b7873fb6b2b37876d23ddb34735d6905e1963e32d548ae98570374"}}],"externalParameters":{"configSource":{"path":"Dockerfile"},"request":{"frontend":"gateway.v0","args":{"cmdline":"docker/dockerfile:1.7-labs","context:metalsrc":"local:metalsrc","frontend.caps":"moby.buildkit.frontend.contexts+forward","sharedkey:localdir:metalsrc":"metalsrc:4e7665ce329afc22","source":"docker/dockerfile:1.7-labs"},"locals":[{"name":"context"},{"name":"dockerfile"},{"name":"metalsrc"}],"root":{"configSource":{"path":"Dockerfile"},"request":{"args":{"context:metalsrc":"local:metalsrc","frontend.caps":"moby.buildkit.frontend.contexts+forward","sharedkey:localdir:metalsrc":"metalsrc:4e7665ce329afc22"}}},"compatibilityVersion":30}},"internalParameters":{"builderPlatform":"linux/amd64"}},"runDetails":{"builder":{"id":""},"metadata":{"invocationId":"77b5wsv5a89cez5aimax5aqjj","startedOn":"2026-11-29T05:07:03.349053106Z","finishedOn":"2026-11-29T05:07:09.472315493Z","buildkit_metadata":{},"buildkit_completeness":{"request":false,"resolvedDependencies":false}}}}} \ No newline at end of file diff --git a/image/blobs/sha256/fdd5150ca1a0c2c722f552dda7ed3deaaa9289294931aca6825aed95c2ce4760 b/image/blobs/sha256/fdd5150ca1a0c2c722f552dda7ed3deaaa9289294931aca6825aed95c2ce4760 new file mode 100644 index 0000000000000000000000000000000000000000..1899d713e48122f187d6d5c5c4689e392709cac3 Binary files /dev/null and b/image/blobs/sha256/fdd5150ca1a0c2c722f552dda7ed3deaaa9289294931aca6825aed95c2ce4760 differ diff --git a/image/blobs/sha256/fed26da465205879ddefd477dede4d90fccc48b762849d028c45f589ea4bf6f4 b/image/blobs/sha256/fed26da465205879ddefd477dede4d90fccc48b762849d028c45f589ea4bf6f4 new file mode 100644 index 0000000000000000000000000000000000000000..7ec50038d2ab035e3e011cc0bda19fb14c6d223d --- /dev/null +++ b/image/blobs/sha256/fed26da465205879ddefd477dede4d90fccc48b762849d028c45f589ea4bf6f4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fed26da465205879ddefd477dede4d90fccc48b762849d028c45f589ea4bf6f4 +size 801689 diff --git a/image/index.json b/image/index.json new file mode 100644 index 0000000000000000000000000000000000000000..c8bfb132f28b6fc5276dc67b8a862b1eeb1f5301 --- /dev/null +++ b/image/index.json @@ -0,0 +1 @@ +{"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json","manifests":[{"mediaType":"application/vnd.oci.image.index.v1+json","digest":"sha256:8405af31ce627ee3d18eb7e0bf0aa8c4d8c2e8625851e733d98a8bfdbc1cfeba","size":856,"annotations":{"io.containerd.image.name":"docker.io/tt-model/depthpro2:8405af31ce62","org.opencontainers.image.ref.name":"8405af31ce62"}}]} \ No newline at end of file diff --git a/image/manifest.json b/image/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..1831b832381e3e01869ecad009bdcbd98a6717dd --- /dev/null +++ b/image/manifest.json @@ -0,0 +1 @@ +[{"Config":"blobs/sha256/34020e6601d2b3b40db6cdfec30536e8a7b15b6b0c9612cd2fa29f21a7eee863","RepoTags":["tt-model/depthpro2:8405af31ce62"],"Layers":["blobs/sha256/ba082564e6605eeb2e1abc91a762985d2e8afea393433de08e798c1eee36d028","blobs/sha256/671912666b1102907184fdf4478ef31010aaa5d3e790c872ed63a6f305af1674","blobs/sha256/fdd5150ca1a0c2c722f552dda7ed3deaaa9289294931aca6825aed95c2ce4760","blobs/sha256/d43baab0c30010379faae769137459154234a3db3176feafda3ba268ba069d0f","blobs/sha256/a90d913a3b293654e45a902690e86ee0a9cbee6dac59ccc9b8f5b6dcf70acfa0","blobs/sha256/b5d78d46efec8b21102fcabc61b536b7c710fa075c56cc5573c7f25d000b2958","blobs/sha256/5b016d79bb0d0f231feb56432bca597d22372330cae9fcbd57b66a767a0e0bde","blobs/sha256/6b84c4b1e198fcf5606226d8bcbcb2bee61c8c2d7e45e4a24ebb077d51e7dbb9","blobs/sha256/e5758dccd78c32a99fa2ad6fede7dcdc9a010195d5b2e52fdf578ad053a5efe1","blobs/sha256/8ea3df7e57eca539aaef3886da4416edc8049442de5819442ff93435714efda2","blobs/sha256/1431ca2d06bf0e3d6b058e48861af84ab9e0a76124a34cfc8668fbc33128cf31","blobs/sha256/b2c200cde9649039e625dcd0b97cb038730866e1eea1f36fa1ade18f52890b37","blobs/sha256/bd2a1526ee7e957e7890edc94a56b8d87c4106f128c96d3dfc5dbe5c6ca324d4","blobs/sha256/26978a700289f033dd9238f908fb9bde859d9bf209a916db1a441ef7f08bbbcd","blobs/sha256/8e640e05879de6ee1f5a3a511bd4907cc6fa5811d23ec76da3f9a4f7aec55599","blobs/sha256/fed26da465205879ddefd477dede4d90fccc48b762849d028c45f589ea4bf6f4","blobs/sha256/4f4fb700ef54461cfa02571ae0db9a0dc1e0cdb5577484a6d75e68dc38e8acc1","blobs/sha256/a78d4158910533ecef000d98be19cc62db3ace7841507634f52935afcdb587ad","blobs/sha256/8dbb9dc6159f3f43fbb2af7bbc5ee536597279b22e23412ee49b4fb346a8f6ae","blobs/sha256/4f4fb700ef54461cfa02571ae0db9a0dc1e0cdb5577484a6d75e68dc38e8acc1","blobs/sha256/599e044f5d508c6d7465d5c227174c066871016ed5afbea49f73a5b588c68a63","blobs/sha256/a0f9120f8473031e9c31209f61fc7dd3ab859a2dfb3001d7dfd8b5996df48b72","blobs/sha256/d068284065b9a015a2304692ae9ecfb3eb7886643b8dc12dd2d1123c1688a40f"]}] \ No newline at end of file diff --git a/image/oci-layout b/image/oci-layout new file mode 100644 index 0000000000000000000000000000000000000000..1343d370fa7b18a594705346b415d647f611a1d1 --- /dev/null +++ b/image/oci-layout @@ -0,0 +1 @@ +{"imageLayoutVersion":"1.0.0"} \ No newline at end of file diff --git a/patches/README.md b/patches/README.md new file mode 100644 index 0000000000000000000000000000000000000000..70c1b58df1a333f0aef29580d5bae0ad5f21e169 --- /dev/null +++ b/patches/README.md @@ -0,0 +1,13 @@ +# tt-metal patches + +The image is built from tt-metal `44d66500520fda9f2c7060c0f6b41ec48f7ab37e` (main, `v0.80.0-dev20261006-78`) with +these two patches applied (together they are the whole diff of that tree; the card's Provenance shows it as a +"dirty tree"): + +| patch | what it does | sha256 | +| --- | --- | --- | +| [`tt-metal-eth-dispatch.patch`](tt-metal-eth-dispatch.patch) | Device dispatch on the idle Ethernet cores of a single p150, so the full 12 x 10 Tensix grid (120 cores) is free for the model (`DispatchCoreConfig(DispatchCoreType.ETH)`); without it the device opens with WORKER dispatch and an 11 x 10 grid | `08d0ddf68664a13a2be93b157c60d7d484b1cf9544f4f201139daf60dae045cc` | +| [`tt-metal-reshape-rm-sys1419.patch`](tt-metal-reshape-rm-sys1419.patch) | A guard in the row-major `ttnn.reshape` program factory against a dispatch hang under ETH dispatch when it writes DRAM pages smaller than 4 KB | `6be07ce5bc9be0621264a040e5508dafc530a3bd9e4256c8dc0679ec9ab74cfa` | + +To run the Python API outside the container, build tt-metal at that commit with both patches applied +(`git apply patches/*.patch` in the tt-metal checkout before `./build_metal.sh`). License: Apache-2.0, as tt-metal. diff --git a/patches/tt-metal-eth-dispatch.patch b/patches/tt-metal-eth-dispatch.patch new file mode 100644 index 0000000000000000000000000000000000000000..61fd39d1858b3e345c201c2a498423efd79dd753 --- /dev/null +++ b/patches/tt-metal-eth-dispatch.patch @@ -0,0 +1,84 @@ +diff --git a/tt_metal/hw/toolchain/main.ld b/tt_metal/hw/toolchain/main.ld +index 8cee67693d8..03732862192 100644 +--- a/tt_metal/hw/toolchain/main.ld ++++ b/tt_metal/hw/toolchain/main.ld +@@ -306,7 +306,8 @@ SECTIONS + LONG(TEXT_SIZE + #if defined(TYPE_KERNEL) && !(defined(COMPILE_FOR_NCRISC) && defined(ARCH_WORMHOLE)) \ + && !defined(COMPILE_FOR_AERISC) && !defined(COMPILE_FOR_SUBORDINATE_AERISC) \ +- && !defined(COMPILE_FOR_MAIN_AERISC) ++ && !defined(COMPILE_FOR_MAIN_AERISC) \ ++ && !(defined(ARCH_BLACKHOLE) && (defined(COMPILE_FOR_IERISC) || defined(COMPILE_FOR_SUBORDINATE_IERISC))) + - (__fw_export_text_end - TEXT_START) + #endif + ) +diff --git a/tt_metal/impl/dispatch/dispatch_query_manager.cpp b/tt_metal/impl/dispatch/dispatch_query_manager.cpp +index 38c31376178..fef7bafe6cd 100644 +--- a/tt_metal/impl/dispatch/dispatch_query_manager.cpp ++++ b/tt_metal/impl/dispatch/dispatch_query_manager.cpp +@@ -148,6 +148,15 @@ void DispatchQueryManager::reset(DispatchCoreConfig& dispatch_core_config, uint8 + (num_hw_cqs == 1 or dispatch_core_config_.get_dispatch_core_type() == DispatchCoreType::WORKER); + distributed_dispatcher_ = + (num_hw_cqs == 1 and dispatch_core_config_.get_dispatch_core_type() == DispatchCoreType::ETH); ++ // Blackhole ETH dispatch with 1 CQ needs 3 idle ETH cores (prefetch, dispatch, dispatch_s). ++ // Galaxy BH chips only have 2 idle ETH cores (the rest are trained links), so fall back to ++ // running without dispatch_s (dispatch_d sends go signals), which needs only 2 cores. ++ if (arch == tt::ARCH::BLACKHOLE and num_hw_cqs == 1 and ++ dispatch_core_config_.get_dispatch_core_type() == DispatchCoreType::ETH and ++ populate_all_logical_dispatch_cores(env_, num_hw_cqs_, dispatch_core_config_).size() < 3) { ++ dispatch_s_enabled_ = false; ++ distributed_dispatcher_ = false; ++ } + } + + go_signal_noc_ = (dispatch_s_enabled_ and arch != tt::ARCH::QUASAR) ? NOC::NOC_1 : NOC::NOC_0; +diff --git a/tt_metal/impl/dispatch/topology.cpp b/tt_metal/impl/dispatch/topology.cpp +index 3dc6377b652..813787a2bf5 100644 +--- a/tt_metal/impl/dispatch/topology.cpp ++++ b/tt_metal/impl/dispatch/topology.cpp +@@ -130,6 +130,12 @@ static const std::vector single_chip_arch_1cq = { + {2, 0, 0, 0, DISPATCH_S, {0, x, x, x}, {1, x, x, x}, k_dispatcher_s_noc}, + }; + ++// 1 CQ without dispatch_s (used for Blackhole ETH dispatch when only 2 idle ETH cores exist) ++static const std::vector single_chip_arch_1cq_no_dispatch_s = { ++ {0, 0, 0, 0, PREFETCH_HD, {x, x, x, x}, {1, x, x, x}, k_prefetcher_noc}, ++ {1, 0, 0, 0, DISPATCH_HD, {0, x, x, x}, {x, x, x, x}, k_dispatcher_noc}, ++}; ++ + static const std::vector single_chip_arch_2cq = { + {0, 0, 0, 0, PREFETCH_HD, {x, x, x, x}, {2, x, x, x}, k_prefetcher_noc}, + {1, 0, 0, 1, PREFETCH_HD, {x, x, x, x}, {3, x, x, x}, k_prefetcher_noc}, +@@ -464,7 +470,13 @@ std::vector DispatchTopology::generate_nodes( + auto populate_single_device = [&]() { + const bool is_quasar = this->descriptor_.cluster().arch() == tt::ARCH::QUASAR; + if (num_hw_cqs == 1) { +- return is_quasar ? quasar_single_chip_1cq : single_chip_arch_1cq; ++ if (is_quasar) { ++ return quasar_single_chip_1cq; ++ } ++ if (!this->get_dispatch_query_manager_().dispatch_s_enabled()) { ++ return single_chip_arch_1cq_no_dispatch_s; ++ } ++ return single_chip_arch_1cq; + } + if (is_quasar) { + return quasar_single_chip_2cq; +diff --git a/tt_metal/llrt/core_descriptor.cpp b/tt_metal/llrt/core_descriptor.cpp +index 0ada4eff2f0..1a2358d6cf7 100644 +--- a/tt_metal/llrt/core_descriptor.cpp ++++ b/tt_metal/llrt/core_descriptor.cpp +@@ -290,6 +290,13 @@ const tt::core_descriptor_t& MetalEnvImpl::get_core_descriptor_config( + coord = RelativeCoreCoord({.x = core_node[0].as(), .y = core_node[1].as()}); + if (get_core_type_from_config(dispatch_core_config) == CoreType::ETH) { + auto logical_coord = get_core_coord_from_relative(coord, grid_size); ++ // Skip ETH dispatch entries that do not exist on this chip (harvested ETH cores, e.g. ++ // Blackhole Galaxy chips expose fewer than the 14 ETH cores listed in the YAML). ++ const size_t num_logical_eth_cores = ++ get_cluster().get_soc_desc(device_id).get_cores(CoreType::ETH, CoordSystem::LOGICAL).size(); ++ if (logical_coord.y >= num_logical_eth_cores) { ++ continue; ++ } + if (logical_active_eth_cores.contains(logical_coord)) { + continue; + } diff --git a/patches/tt-metal-reshape-rm-sys1419.patch b/patches/tt-metal-reshape-rm-sys1419.patch new file mode 100644 index 0000000000000000000000000000000000000000..bc7caf76076bdafa2b8816986c35c5a7573b232f --- /dev/null +++ b/patches/tt-metal-reshape-rm-sys1419.patch @@ -0,0 +1,53 @@ +# tt-metal 44d6650: avoid the dual-kernel ROW_MAJOR reshape for small DRAM destination pages on Blackhole (SYS-1419). +# Root fix for the ETH-dispatch hang of logs/meteor/hangfix/ETH_DISPATCH_HANG_ISSUE.md. Apply with: git -C tt-metal apply +# (Applied to the workspace tt-metal tree on 2026-10-10 and carried by every image built since; the image verify step checks for it). Override: TT_METAL_RESHAPE_RM_DUAL_DRAM_MIN_PAGE_BYTES= (0 = old behaviour). +--- a/ttnn/cpp/ttnn/operations/data_movement/reshape_view/device/reshape_rm_program_factory.cpp 2026-10-10 09:31:29.732524814 +0000 ++++ b/ttnn/cpp/ttnn/operations/data_movement/reshape_view/device/reshape_rm_program_factory.cpp 2026-10-10 10:05:49.865294200 +0000 +@@ -5,6 +5,7 @@ + #include "ttnn/operations/data_movement/reshape_view/device/reshape_row_major_program_factory.hpp" + + #include ++#include + + #include + #include +@@ -33,6 +34,26 @@ + // wide destinations stop fitting in L1. + constexpr uint32_t small_dest_write_slots = 8; + ++// Blackhole SYS-1419: the DRAM arbiter can drop requests when both NOCs issue requests to the same DRAM endpoint at ++// a high rate (tests/tt_metal/tt_metal/api/test_dram.cpp, DISABLED_TensixLoopDRAMReadSingleCoreBothProcessors). The ++// dual-kernel split below has the reader- and writer-config instances (one per NOC) each write destination pages to ++// interleaved DRAM; with small destination pages that is a stream of small DRAM writes from both NOCs. Measured on ++// a p150 (ETH dispatch, 12x10, one traced reshape of a bf16 ROW_MAJOR [1, 1, 800, 48000] replayed back to back): ++// 192 B destination pages deadlock at replay 363, 384 B at replay 162; 512 B, 1 KB and 4 KB pages ran 20,000 replays ++// clean (WORKER dispatch: 192 B clean for 3,000). Below this destination page size the single-kernel path is used for ++// DRAM destinations (4 KB: a margin over the largest failing size). ++// TT_METAL_RESHAPE_RM_DUAL_DRAM_MIN_PAGE_BYTES overrides it (0 restores the old behaviour). ++constexpr uint32_t dual_kernel_min_dram_dest_page_bytes_default = 4096; ++ ++uint32_t dual_kernel_min_dram_dest_page_bytes() { ++ static const uint32_t value = [] { ++ const char* env = std::getenv("TT_METAL_RESHAPE_RM_DUAL_DRAM_MIN_PAGE_BYTES"); ++ return env != nullptr ? static_cast(std::strtoul(env, nullptr, 10)) ++ : dual_kernel_min_dram_dest_page_bytes_default; ++ }(); ++ return value; ++} ++ + // Kept local (not a shared header): Quasar's factory is an intentional mirror of this + // file; a cross-op helper would only dedupe ~30 lines and add CMake/packaging coupling. + // Non-clean dest staging uses a multi-slot L1 ring. Cap slots by per-core L1 budget so +@@ -124,7 +145,11 @@ + // Avoid dual-kernel when dest writes are too small for DRAM (Blackhole SYS-1419 / #50191). + // Only dest alignment matters: source alignment selects the clean-vs-staging read path + // but doesn't affect the size of writes hitting DRAM. +- const bool can_use_dual_kernel = pages_divisible && (dest_noc_aligned || !dst_buffer->is_dram()); ++ // ... and avoid it for small DRAM destination pages from both NOCs on Blackhole (SYS-1419, see above). ++ const bool small_dram_dest_writes = dst_buffer->is_dram() && device->arch() == tt::ARCH::BLACKHOLE && ++ dest_page_size_bytes < dual_kernel_min_dram_dest_page_bytes(); ++ const bool can_use_dual_kernel = ++ pages_divisible && (dest_noc_aligned || !dst_buffer->is_dram()) && !small_dram_dest_writes; + + const uint32_t num_dest_write_slots = choose_num_dest_write_slots( + *device, pages_noc_aligned, can_use_dual_kernel, scratch_size0, dest_slot_size_bytes); diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..2b47305f07ed1d9ff5382f71501d84995ca2a75c --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,59 @@ +# SPDX-License-Identifier: Apache-2.0 +# Python package of DepthPro2 (changh95/DepthPro2), from the ROOT of the model repo: +# pip install -e . # the Python API +# pip install -e ".[server,test]" # + the HTTP server and the tests +# +# Install it into an environment that already has tt-metal's ttnn (and its torch 2.11.0+cpu): ttnn and torch are NOT +# declared, so pip never replaces the tt-metal build's own torch. The container image installs the same set through +# tt-model.yaml runtime.packages (pinned there to the versions the gates ran with). +# +# This file lives at the repo root ON PURPOSE and must never move into code/: tt-model copies code/ over /opt/tt-metal +# right before `uv pip install -e /opt/tt-metal` in the image build, so a code/pyproject.toml would replace tt-metal's +# own (project ttnn) and break `import ttnn` in the image. It is not in tt-model.yaml extra_code: it reaches the Hub as +# an overlay file next to the generated README.md. +[build-system] +requires = ["setuptools>=77"] +build-backend = "setuptools.build_meta" + +[project] +name = "tt-depthpro2" +dynamic = ["version"] # tt_depthpro2.__version__, the version /openapi.json reports +description = "Apple Depth Pro 2 (S, B, L, H+) metric depth on Tenstorrent Blackhole p150 (tt-nn), with a Python API and an HTTP server" +readme = "code/PYTHON.md" +license = "Apache-2.0" # the port's code; the weights (not included) are under Apple's research-only licence +requires-python = ">=3.10" +dependencies = [ + "numpy>=1.24.4,<2", # ttnn needs numpy 1.x + "pillow", # image decoding, 16-bit PNG output + "safetensors", # apple/DepthPro2-* model.safetensors + "huggingface_hub", # weights pointers: apple/DepthPro2-{S,B,L,H,focal} at pinned commits +] + +[project.optional-dependencies] +server = ["fastapi", "uvicorn", "pydantic>=2"] +test = ["pytest", "httpx"] + +[project.urls] +"Model card" = "https://huggingface.co/changh95/DepthPro2" +"Weights" = "https://huggingface.co/apple/DepthPro2" +"Official code" = "https://github.com/apple-aiml-research/ml-depth-pro-2" + +[tool.setuptools.dynamic] +version = { attr = "tt_depthpro2.__version__" } + +[tool.setuptools.packages.find] +where = ["code"] # import root (code/conftest.py and code/scripts/ are not packaged) +include = ["tt_depthpro2*"] # with the vendored tt_depthpro2.ttaw (common/tools/vendor.py; never edit it) +exclude = ["tt_depthpro2.tests*"] + +[tool.setuptools.package-data] +"tt_depthpro2" = ["samples/*/*", "licenses/*"] +"tt_depthpro2.tt" = ["kernels/*"] # device kernels, JIT-compiled at the first start +"tt_depthpro2.tt.mk_enc" = ["kernels/*.cpp", "kernels/*.hpp", "kernels/*.h"] +"tt_depthpro2.tt.mk_dec" = ["kernels/*.cpp", "kernels/*.hpp", "kernels/*.h"] +"tt_depthpro2.tt.mk_fov" = ["kernels/*.cpp", "kernels/*.hpp", "kernels/*.h"] +"tt_depthpro2.ttaw" = ["API.md", "VENDORED.json"] +"tt_depthpro2.ttaw.ops" = ["kernels/*.cpp", "kernels/*.hpp", "kernels/*.h"] + +[tool.pytest.ini_options] +markers = ["device: needs a Tenstorrent chip (skipped on host-only runs)"] diff --git a/requirements.lock b/requirements.lock new file mode 100644 index 0000000000000000000000000000000000000000..84c722bd2e8b6af825b5a509ca11f292a1e02e03 --- /dev/null +++ b/requirements.lock @@ -0,0 +1,79 @@ +annotated-doc==0.0.7 +annotated-types==0.8.0 +anyio==4.16.0 +certifi==2026.11.20 +cfgv==3.5.0 +charset-normalizer==3.5.3 +click==8.5.1 +contourpy==1.3.3 +cycler==0.12.1 +distlib==0.4.4 +distro==1.9.0 +elastic-transport==9.4.3 +elasticsearch==9.5.1 +fastapi==0.142.2 +filelock==4.3.2 +fonttools==4.69.1 +fsspec==2026.9.0 +graphviz==0.21 +h11==0.16.0 +hf-xet==1.8.0 +httpcore==1.0.9 +httpx==0.29.0 +huggingface_hub==1.16.1 +identify==2.6.20 +idna==3.20 +Jinja2==3.1.6 +kiwisolver==1.5.1 +linkify-it-py==2.2.0 +loguru==0.8.0 +markdown-it-py==4.3.0 +MarkupSafe==3.0.4 +matplotlib==3.11.2 +mdit-py-plugins==0.7.0 +mdurl==0.1.2 +ml_dtypes==0.5.4 +mpmath==1.3.0 +networkx==3.7 +nodeenv==1.12.0 +numpy==1.26.4 +opentelemetry-api==1.45.2 +packaging==26.4 +pandas==3.0.6 +pillow==12.3.0 +platformdirs==4.14.9 +pre_commit==4.7.0 +psutil==7.2.2 +pydantic==2.14.4 +pydantic_core==2.50.5 +Pygments==2.21.0 +pyluwen==0.10.0 +pyparsing==3.3.3 +python-dateutil==4.0.0 +python-discovery==1.9.8 +PyYAML==6.0.4 +requests==2.34.2 +rich==15.0.0 +safetensors==0.8.0 +seaborn==0.13.2 +setuptools==80.10.2 +setuptools-scm==8.1.0 +shellingham==1.5.4 +sniffio==1.3.1 +starlette==1.10.0 +sympy==1.14.0 +textual==8.2.8 +tomli==2.5.0 +torch==2.11.0+cpu +tqdm==4.70.1 +tt-smi==6.8.1 +tt-tools-common==1.6.0 +tt-umd==0.9.17 +typer==0.29.3 +typing-inspection==0.4.5 +typing_extensions==4.16.0 +tzdata==2026.6 +urllib3==2.8.0 +uvicorn==0.54.0 +virtualenv==21.15.14 +wheel==0.48.0 diff --git a/tt-model.yaml b/tt-model.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d7e67d8adbdeb583aaacc9edd9835a3c7dd474d --- /dev/null +++ b/tt-model.yaml @@ -0,0 +1,438 @@ +# SPDX-License-Identifier: Apache-2.0 +# tt-model-manager container manifest (schema 5.1): Apple Depth Pro 2 (S, B, L, H+ and the shared focal-length +# estimator) on one Tenstorrent Blackhole p150. The published README.md is GENERATED from the `card:` block below by +# `tt-model package`. +# +# Run EVERY tt-model command FROM THIS DIRECTORY: extra_code[].root resolves against the process CWD; --out must point +# OUTSIDE this directory (package deletes / first). +# ~/.local/share/uv/tools/tt-model/bin/python -c "from tt_kernel.container_manifest import load_container_manifest as L; L('tt-model.yaml', check_sources=True)" +# sg docker -c "tt-model package --container tt-model.yaml --out /build" +# (serve + smoke + stop under the device lock, once per profile: code/scripts/container_smoke.sh 20000 --profile

) +# tt-model push --publish # HF_TOKEN from the environment only +schema: "5.1" + +repo: changh95/DepthPro2 +name: depthpro2 # docker image / container / cache names must be lowercase + +# POINTERS, never baked into the image and never redistributed: `serve` / `pull --with-weights` download exactly these +# files at these commits into the host HF cache (mounted at /hf). Apple's licence (research purposes only) travels +# with every repo (LICENSE). The primary repo is the focal-length estimator every size shares; the four sizes are +# auxiliary weights (tt-model exports them as TT_AUXILIARY_WEIGHTS=repo@rev,...; the server picks DEPTHPRO2_SIZE's). +weights: + repo: apple/DepthPro2-focal + revision: 622659d44a2002cf9ae4333f2569afa938290d9a + allow_patterns: [model.safetensors, config.json, LICENSE, README.md] # 94 MB +auxiliary_weights: + - repo: apple/DepthPro2-S + revision: 903a1c1ade918831d138adcc4aedbcc8f4da0078 + allow_patterns: [model.safetensors, config.json, LICENSE, README.md] # 97 MB + - repo: apple/DepthPro2-B + revision: 85e67fdfb7f5b36a6f6c4495e6789d331b1d8a04 + allow_patterns: [model.safetensors, config.json, LICENSE, README.md] # 386 MB + - repo: apple/DepthPro2-L + revision: 849dc5461267e0bc006ec63ab46920ea1ed98702 + allow_patterns: [model.safetensors, config.json, LICENSE, README.md] # 1.34 GB + - repo: apple/DepthPro2-H + revision: 68426c789f75a7c760273e857222625b4fe69576 + allow_patterns: [model.safetensors, config.json, LICENSE, README.md] # 3.49 GB + +kind: tt-dit-server # the model's own FastAPI app under uvicorn (not an OpenAI-compatible API) +arch: blackhole + +source: + # tt-metal main 44d6650 (v0.80.0-dev20261006) WITH patches/tt-metal-eth-dispatch.patch and + # patches/tt-metal-reshape-rm-sys1419.patch applied: a dirty tree, packaged as-is. torch 2.11.0 pin read from it. + tt_metal: /home/ubuntu/experiments/tt-models/tt-metal + # Schema minimum (>= 1 path relative to the tt-metal tree). The port imports nothing from tt-metal's models/. + code: + - models/common/lightweightmodule.py + # The port itself: copied over /opt/tt-metal/ in the image (PYTHONPATH=/opt/tt-metal); code/ on the Hub + # becomes exactly this set at every push. Never a tt-metal build input (pyproject.toml lives at the repo root). + extra_code: + - root: code + paths: + - tt_depthpro2 # API, server, smoke test, device programs, reference, tests, sample, licences + - scripts/bench.py # latency per bucket and clip length (device, Python call, served) + - scripts/bench_baseline.py # traced device time per stage (ENC / DEC / FOV / KV step) + - scripts/make_sample_reference.py # regenerates the sample's stored CPU-reference outputs + - scripts/make_demo.py # renders media/demo_sample.png from a served response + - scripts/device_server_smoke.py # serving gate on the host: the app on the device vs goldens / CPU engine + - scripts/container_smoke.sh # serve one profile, smoke, always stop + - conftest.py + - PYTHON.md + ubuntu: "22.04" + python: "3.12" + +runtime: + app: tt_depthpro2.server.app:app + mesh_shape_env: TT_MESH_SHAPE + # On top of the kind defaults (fastapi, uvicorn, pydantic>=2, pillow) and the auto-pinned torch==2.11.0+cpu: every + # third-party module on the serve path, pinned to the versions the host tests ran with. No video decoder: the + # server takes frames (PNG / JPEG / a uint8 .npy); client.py decodes video files on the client. + packages: + - "numpy>=1.24.4,<2" + - safetensors==0.8.0 + - huggingface_hub==1.16.1 # snapshots of the pinned weights + - pillow==12.3.0 # image decoding, 16-bit PNG output + - fastapi==0.142.2 + - uvicorn==0.54.0 + +serve: + port: 20000 + hardware: p150 + mesh_device: P150 + env: + TT_WEIGHTS_REVISION: "622659d44a2002cf9ae4333f2569afa938290d9a" # == weights.revision (the focal estimator) + TT_METAL_VISIBLE_DEVICES: "0" + TT_DEVICE_ID: "0" + # Apple's repos are public and ungated: never send a token. serve mounts the host HF cache (which may hold a + # stored token file) at /hf, so huggingface_hub must not pick one up implicitly. + HF_HUB_DISABLE_IMPLICIT_TOKEN: "1" + # ETH dispatch: the 12x10 grid every published number uses; the smoke test fails on anything else. + DEPTHPRO2_DISPATCH: "eth" + DEPTHPRO2_NUM_CQS: "1" + # The configuration, read once when the server starts (the device programs are compiled for it; a bad value + # refuses to start). The profiles below set DEPTHPRO2_SIZE. + DEPTHPRO2_SIZE: "L" + DEPTHPRO2_RESOLUTIONS: "vga,vga_portrait" # 480x640 and 640x480; other sizes are resized to the nearest aspect + DEPTHPRO2_WINDOW: "16" # video clip length (the official default) + DEPTHPRO2_OVERLAP: "4" # buffered overlap (the official default) + DEPTHPRO2_VIDEO_MODES: "auto" # buffered + unbuffered when the unbuffered caches fit 4 GB (they do + # for every size at the default buckets / window: SERVING.md 4) + DEPTHPRO2_KV_STREAMS: "1" # unbuffered streams open at once (one key-value cache per bucket) + DEPTHPRO2_FOV: "1" + DEPTHPRO2_TORCH_THREADS: "4" + # The shipped engines (gated + soaked): encoder, decoder and focal-estimator trunk as persistent megakernels; + # any stage can fall back to its tt-nn ops (e.g. DEPTHPRO2_ENGINE=enc=mk,dec=ttnn,fov=mk). + DEPTHPRO2_ENGINE: "enc=mk,dec=mk,fov=mk" + +serve_profiles: + - name: s + description: "Depth Pro 2 S (24M parameters): the fastest" + env: {DEPTHPRO2_SIZE: "S"} + - name: b + description: "Depth Pro 2 B (97M parameters)" + env: {DEPTHPRO2_SIZE: "B"} + - name: l + description: "Depth Pro 2 L (334M parameters): the default" + env: {DEPTHPRO2_SIZE: "L"} + - name: h + description: "Depth Pro 2 H+ (872M parameters): the most accurate" + env: {DEPTHPRO2_SIZE: "H"} +default_profile: l + +# Build-time assertions, run INSIDE the finished image as uid 1000, without a device or weights. +verify: + # the image carries the ETH-dispatch patch (12x10 grid) and the SYS-1419 reshape guard + - "assert 'single_chip_arch_1cq_no_dispatch_s' in open('/opt/tt-metal/tt_metal/impl/dispatch/topology.cpp').read()" + - "assert 'dual_kernel_min_dram_dest_page_bytes' in open('/opt/tt-metal/ttnn/cpp/ttnn/operations/data_movement/reshape_view/device/reshape_rm_program_factory.cpp').read()" + - "from tt_depthpro2.ttaw.device import eth_dispatch_patch_present as p; assert p(), 'ttaw does not see the ETH patch'" + # the server imports without side effects; the mesh parser; the serve env resolves to the pinned configuration + - "import sys, tt_depthpro2.server.app as a; assert a.app and 'ttnn' not in sys.modules and 'torch' not in sys.modules, 'the server module must import without ttnn / torch'" + - "from tt_depthpro2.server.app import parse_mesh_shape as p; assert p('1x1') == p('(1, 1)') == p('1,1') == (1, 1)" + - "from tt_depthpro2.server.app import load_config; c = load_config({'DEPTHPRO2_SIZE': 'L', 'DEPTHPRO2_RESOLUTIONS': 'vga,vga_portrait', 'DEPTHPRO2_WINDOW': '16', 'DEPTHPRO2_OVERLAP': '4', 'DEPTHPRO2_VIDEO_MODES': 'auto', 'DEPTHPRO2_KV_STREAMS': '1', 'DEPTHPRO2_FOV': '1', 'DEPTHPRO2_DISPATCH': 'eth', 'DEPTHPRO2_NUM_CQS': '1', 'DEPTHPRO2_ENGINE': 'enc=mk,dec=mk,fov=mk', 'TT_AUXILIARY_WEIGHTS': 'apple/DepthPro2-S@903a1c1ade918831d138adcc4aedbcc8f4da0078,apple/DepthPro2-B@85e67fdfb7f5b36a6f6c4495e6789d331b1d8a04,apple/DepthPro2-L@849dc5461267e0bc006ec63ab46920ea1ed98702,apple/DepthPro2-H@68426c789f75a7c760273e857222625b4fe69576', 'TT_MODEL_WEIGHTS_REVISION': '622659d44a2002cf9ae4333f2569afa938290d9a'}); m = c.model; assert m.engine == {'enc': 'mk', 'dec': 'mk', 'fov': 'mk'}, m.engine; assert (m.size, m.resolutions, m.window, m.overlap, m.video_modes, m.video_modes_auto, m.kv_streams, m.clip_lengths, m.fov, c.dispatch, c.num_command_queues, c.revision, c.fov_revision) == ('L', ((480, 640), (640, 480)), 16, 4, ('buffered', 'unbuffered'), True, 1, (1, 16), True, 'eth', 1, '849dc5461267e0bc006ec63ab46920ea1ed98702', '622659d44a2002cf9ae4333f2569afa938290d9a'), c" + # a bad configuration refuses to start + - "from tt_depthpro2.server.app import load_config as L\nfor bad in ({'DEPTHPRO2_SIZE': 'XL'}, {'DEPTHPRO2_RESOLUTIONS': '480x'}, {'DEPTHPRO2_WINDOW': '17'}, {'DEPTHPRO2_OVERLAP': '16'}, {'DEPTHPRO2_VIDEO_MODES': 'live'}, {'DEPTHPRO2_KV_STREAMS': '0'}, {'DEPTHPRO2_ENGINE': 'dec=gpu'}, {'TT_MESH_SHAPE': '1x2'}):\n try:\n L(bad)\n except RuntimeError:\n continue\n raise AssertionError(bad)" + # the weights pins (focal + the four sizes) + - "from tt_depthpro2.config import WEIGHTS; assert WEIGHTS == {'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 API, the CPU engine, the streaming and the reference import (torch, no device) + - "import tt_depthpro2.api, tt_depthpro2.cpu_engine, tt_depthpro2.streaming, tt_depthpro2.reference.model as R; assert R.SIZES['H'].swiglu and tt_depthpro2.api.plan_buffered_clips(10, 4, 1) == [4, 4, 4]" + # the device module: the DepthPro2Device API the server uses, its sizing helpers, and the megakernel sources + # (JIT-compiled at the first start) shipped as files + - "from tt_depthpro2.tt.model import DepthPro2Device as D, trace_region_bytes, planned_frames, kv_state_bytes; import inspect; p = inspect.signature(D).parameters; assert D.supports_kv_cache and all(k in p for k in ('fov_shapes', 'clip_lengths', 'precision', 'kv_cache', 'kv_streams')) and hasattr(D, 'inverse_depth_step') and trace_region_bytes('L', [(480, 640), (640, 480)], [1, 16], kv_cache=True) > (64 << 20)" + - "import importlib.util; from pathlib import Path; d = Path('/opt/tt-metal/tt_depthpro2/tt'); assert all((d / f'mk_enc/kernels/me_{r}.cpp').is_file() and (d / f'mk_dec/kernels/md_{r}.cpp').is_file() for r in ('brisc', 'ncrisc', 'trisc')) and all(importlib.util.find_spec(f'tt_depthpro2.tt.{m}') for m in ('mk_enc', 'mk_fov', 'mk_dec'))" + - "from pathlib import Path; d = Path('/opt/tt-metal/tt_depthpro2/tt'); n = {p.name for p in (d / 'mk_enc' / 'kernels').iterdir()}; m = {p.name for p in (d / 'mk_dec' / 'kernels').iterdir()}; assert {'me_brisc.cpp', 'me_ncrisc.cpp', 'me_trisc.cpp', 'me_defs.hpp', 'me_dm.hpp'} <= n and {'md_brisc.cpp', 'md_ncrisc.cpp', 'md_trisc.cpp', 'md_defs.hpp'} <= m, (n, m)" + # the default engines: the three megakernels; each stage can fall back to tt-nn + - "from tt_depthpro2.config import DEFAULT_ENGINE, resolve_config; assert DEFAULT_ENGINE == {'enc': 'mk', 'dec': 'mk', 'fov': 'mk'} and resolve_config(env={}).engine == DEFAULT_ENGINE and resolve_config(env={'DEPTHPRO2_ENGINE': 'dec=ttnn'}).engine == {'enc': 'mk', 'dec': 'ttnn', 'fov': 'mk'}" + # the shipped sample (CC0), its stored CPU-reference outputs for every size, the licence notice, the scripts + - "import hashlib, json; from pathlib import Path; d = Path('/opt/tt-metal/tt_depthpro2/samples/kropa_street'); assert hashlib.sha256((d / 'image.jpg').read_bytes()).hexdigest() == 'dee4f3aafb7a1724d251e9af56ad9cd5eebbb95289ff63f4cdc1a2e0609445ae' and (d / 'PROVENANCE.md').is_file() and all(json.loads((d / f'reference.{s}.json').read_text())['size'] == s and (d / f'reference.{s}.npy').is_file() for s in 'SBLH')" + - "from pathlib import Path; d = Path('/opt/tt-metal/tt_depthpro2/licenses'); assert 'Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement.' in (d / 'NOTICE.md').read_text() and 'Research Purposes' in (d / 'APPLE_MLR_MODEL_LICENSE.txt').read_text() and (d / 'APPLE_SOFTWARE_LICENSE.txt').read_text().startswith('Copyright (C) 2026 Apple Inc.')" + - "from pathlib import Path; assert all(Path('/opt/tt-metal', p).is_file() for p in ('tt_depthpro2/server/smoke_test.py', 'tt_depthpro2/server/client.py', 'scripts/bench.py', 'scripts/container_smoke.sh', 'scripts/make_sample_reference.py', 'scripts/make_demo.py', 'scripts/device_server_smoke.py'))" + # the dependencies, at the versions the tests ran with + - "import numpy; assert int(numpy.__version__.split('.')[0]) < 2, numpy.__version__" + - "import safetensors, huggingface_hub, PIL, fastapi, uvicorn; assert (safetensors.__version__, PIL.__version__) == ('0.8.0', '12.3.0'), (safetensors.__version__, PIL.__version__)" + - "import torch; assert torch.__version__.startswith('2.11.0'), torch.__version__" + - "import ttnn; assert all(hasattr(ttnn, a) for a in ('DispatchCoreConfig', 'begin_trace_capture', 'end_trace_capture', 'execute_trace', 'release_trace', 'copy_host_to_device_tensor', 'generic_op'))" + +card: + # Facts and measurements of the shipped package only (the model-card-standardizer field guide). + attribution: >- + 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. + + description: >- + 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). + + 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: | + - 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: | + 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: + + ```bash + curl -sLO https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/samples/kropa_street/image.jpg + python3 -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.json + curl -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'])" + ``` + + usage: | + `POST /predict` takes one base64 image and returns its depth map; `POST /predict_png` takes the raw image file and + returns a 16-bit depth PNG; `POST /predict_video` takes the frames of a clip or video and returns one depth map + per 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 chat + API. + + | 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` and + further `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": "", "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 variables + in the container's launch command (`tt-model serve --print` prints it) and start it again. `GET /config` reports + it. + + | 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's + program. 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) | + + # To fill from the device gates and bench.py (SPEC section 5), one row per size where it applies: + # ACCURACY_TABLE: | eval | S | B | L | H+ | cases | rows: inverse-depth PCC (min over img_vga, img_375x500_pad, + # clip4_240x320), depth AbsRel vs Apple float32 next to Apple's own bf16 drift, f_px relative error, buffered + # video stream_buf_w4o1_n10 (S), the shipped sample vs the stored CPU reference. + # SPEED_TABLE: | speed (batch 1, warm) | input | S | B | L | H+ | rows: device time per image 480x640 (trace + # replay), per 16-frame clip (frames/s), FOV; Python infer(); served /predict timing_ms.total and client round + # trip; then one measurement sentence (host, bench.py arguments, iterations). + 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) in + parentheses: + + | 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's + focal length. Apple's float32 output exists for every case except the 375 x 500 image at L and H+, which is + compared 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. The + focal-length estimator is shared by every size. [1] L's prediction for this image is nearly flat (its inverse + depth 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 1000 + trace 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 (every + size 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+, with + 1 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 640 + with 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 requests + returned float32 depth and inverse depth for every frame, which is part of their time). A served request adds + image 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 start + compiles 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: | + - [changh95/depth-anything-3-p150](https://huggingface.co/changh95/depth-anything-3-p150): Depth Anything 3 metric depth on p150. + + license: + id: other + name: Apple AMLR + link: https://huggingface.co/apple/DepthPro2/blob/main/LICENSE + pipeline_tag: depth-estimation + base_model: + - apple/DepthPro2-L + - apple/DepthPro2-S + - apple/DepthPro2-B + - apple/DepthPro2-H + - apple/DepthPro2-focal diff --git a/tt_kernel_manifest.json b/tt_kernel_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..dd3fa641692c9625dfd049a29762e5759ff73396 --- /dev/null +++ b/tt_kernel_manifest.json @@ -0,0 +1,273 @@ +{ + "schema_version": "5.1", + "name": "depthpro2", + "tt_metal_version": "0.65.2.dev11169+g44d66500520", + "arch": "blackhole", + "device_count": 1, + "producer": { + "tt_kernel_version": "0.1.0", + "created_at": "2026-11-29T05:07:30.292179+00:00", + "hostname": "hchang-bh" + }, + "weights": { + "repo_id": "apple/DepthPro2-focal", + "revision": "622659d44a2002cf9ae4333f2569afa938290d9a", + "allow_patterns": [ + "model.safetensors", + "config.json", + "LICENSE", + "README.md" + ], + "ignore_patterns": null, + "repo_type": "model" + }, + "auxiliary_weights": [ + { + "repo_id": "apple/DepthPro2-S", + "revision": "903a1c1ade918831d138adcc4aedbcc8f4da0078", + "allow_patterns": [ + "model.safetensors", + "config.json", + "LICENSE", + "README.md" + ], + "ignore_patterns": null, + "repo_type": "model" + }, + { + "repo_id": "apple/DepthPro2-B", + "revision": "85e67fdfb7f5b36a6f6c4495e6789d331b1d8a04", + "allow_patterns": [ + "model.safetensors", + "config.json", + "LICENSE", + "README.md" + ], + "ignore_patterns": null, + "repo_type": "model" + }, + { + "repo_id": "apple/DepthPro2-L", + "revision": "849dc5461267e0bc006ec63ab46920ea1ed98702", + "allow_patterns": [ + "model.safetensors", + "config.json", + "LICENSE", + "README.md" + ], + "ignore_patterns": null, + "repo_type": "model" + }, + { + "repo_id": "apple/DepthPro2-H", + "revision": "68426c789f75a7c760273e857222625b4fe69576", + "allow_patterns": [ + "model.safetensors", + "config.json", + "LICENSE", + "README.md" + ], + "ignore_patterns": null, + "repo_type": "model" + } + ], + "mesh": null, + "entrypoint": null, + "resources": null, + "capabilities": null, + "env": {}, + "bundled": null, + "deps": null, + "container": { + "image": { + "registry": "hf", + "repository": "depthpro2", + "tag": "tt-model/depthpro2:8405af31ce62", + "digest": "sha256:8405af31ce627ee3d18eb7e0bf0aa8c4d8c2e8625851e733d98a8bfdbc1cfeba" + }, + "kind": "tt-dit-server", + "runtime": { + "app": "tt_depthpro2.server.app:app", + "mesh_shape_env": "TT_MESH_SHAPE", + "packages": [ + "numpy>=1.24.4,<2", + "safetensors==0.8.0", + "huggingface_hub==1.16.1", + "pillow==12.3.0", + "fastapi==0.142.2", + "uvicorn==0.54.0" + ], + "lock": "requirements.lock" + }, + "serve": { + "hardware": "p150", + "mesh_device": "P150", + "port": 20000, + "max_model_len": null, + "max_num_seqs": null, + "block_size": null, + "server_timeout": null, + "capabilities": null, + "additional_config": {}, + "args": [], + "env": { + "TT_WEIGHTS_REVISION": "622659d44a2002cf9ae4333f2569afa938290d9a", + "TT_METAL_VISIBLE_DEVICES": "0", + "TT_DEVICE_ID": "0", + "HF_HUB_DISABLE_IMPLICIT_TOKEN": "1", + "DEPTHPRO2_DISPATCH": "eth", + "DEPTHPRO2_NUM_CQS": "1", + "DEPTHPRO2_SIZE": "L", + "DEPTHPRO2_RESOLUTIONS": "vga,vga_portrait", + "DEPTHPRO2_WINDOW": "16", + "DEPTHPRO2_OVERLAP": "4", + "DEPTHPRO2_VIDEO_MODES": "auto", + "DEPTHPRO2_KV_STREAMS": "1", + "DEPTHPRO2_FOV": "1", + "DEPTHPRO2_TORCH_THREADS": "4", + "DEPTHPRO2_ENGINE": "enc=mk,dec=mk,fov=mk" + } + }, + "serve_profiles": [ + { + "hardware": null, + "mesh_device": null, + "port": null, + "max_model_len": null, + "max_num_seqs": null, + "block_size": null, + "server_timeout": null, + "capabilities": null, + "additional_config": {}, + "args": [], + "env": { + "DEPTHPRO2_SIZE": "S" + }, + "name": "s", + "description": "Depth Pro 2 S (24M parameters): the fastest" + }, + { + "hardware": null, + "mesh_device": null, + "port": null, + "max_model_len": null, + "max_num_seqs": null, + "block_size": null, + "server_timeout": null, + "capabilities": null, + "additional_config": {}, + "args": [], + "env": { + "DEPTHPRO2_SIZE": "B" + }, + "name": "b", + "description": "Depth Pro 2 B (97M parameters)" + }, + { + "hardware": null, + "mesh_device": null, + "port": null, + "max_model_len": null, + "max_num_seqs": null, + "block_size": null, + "server_timeout": null, + "capabilities": null, + "additional_config": {}, + "args": [], + "env": { + "DEPTHPRO2_SIZE": "L" + }, + "name": "l", + "description": "Depth Pro 2 L (334M parameters): the default" + }, + { + "hardware": null, + "mesh_device": null, + "port": null, + "max_model_len": null, + "max_num_seqs": null, + "block_size": null, + "server_timeout": null, + "capabilities": null, + "additional_config": {}, + "args": [], + "env": { + "DEPTHPRO2_SIZE": "H" + }, + "name": "h", + "description": "Depth Pro 2 H+ (872M parameters): the most accurate" + } + ], + "default_profile": "l", + "code_dir": "code", + "verify": [ + "assert 'single_chip_arch_1cq_no_dispatch_s' in open('/opt/tt-metal/tt_metal/impl/dispatch/topology.cpp').read()", + "assert 'dual_kernel_min_dram_dest_page_bytes' in open('/opt/tt-metal/ttnn/cpp/ttnn/operations/data_movement/reshape_view/device/reshape_rm_program_factory.cpp').read()", + "from tt_depthpro2.ttaw.device import eth_dispatch_patch_present as p; assert p(), 'ttaw does not see the ETH patch'", + "import sys, tt_depthpro2.server.app as a; assert a.app and 'ttnn' not in sys.modules and 'torch' not in sys.modules, 'the server module must import without ttnn / torch'", + "from tt_depthpro2.server.app import parse_mesh_shape as p; assert p('1x1') == p('(1, 1)') == p('1,1') == (1, 1)", + "from tt_depthpro2.server.app import load_config; c = load_config({'DEPTHPRO2_SIZE': 'L', 'DEPTHPRO2_RESOLUTIONS': 'vga,vga_portrait', 'DEPTHPRO2_WINDOW': '16', 'DEPTHPRO2_OVERLAP': '4', 'DEPTHPRO2_VIDEO_MODES': 'auto', 'DEPTHPRO2_KV_STREAMS': '1', 'DEPTHPRO2_FOV': '1', 'DEPTHPRO2_DISPATCH': 'eth', 'DEPTHPRO2_NUM_CQS': '1', 'DEPTHPRO2_ENGINE': 'enc=mk,dec=mk,fov=mk', 'TT_AUXILIARY_WEIGHTS': 'apple/DepthPro2-S@903a1c1ade918831d138adcc4aedbcc8f4da0078,apple/DepthPro2-B@85e67fdfb7f5b36a6f6c4495e6789d331b1d8a04,apple/DepthPro2-L@849dc5461267e0bc006ec63ab46920ea1ed98702,apple/DepthPro2-H@68426c789f75a7c760273e857222625b4fe69576', 'TT_MODEL_WEIGHTS_REVISION': '622659d44a2002cf9ae4333f2569afa938290d9a'}); m = c.model; assert m.engine == {'enc': 'mk', 'dec': 'mk', 'fov': 'mk'}, m.engine; assert (m.size, m.resolutions, m.window, m.overlap, m.video_modes, m.video_modes_auto, m.kv_streams, m.clip_lengths, m.fov, c.dispatch, c.num_command_queues, c.revision, c.fov_revision) == ('L', ((480, 640), (640, 480)), 16, 4, ('buffered', 'unbuffered'), True, 1, (1, 16), True, 'eth', 1, '849dc5461267e0bc006ec63ab46920ea1ed98702', '622659d44a2002cf9ae4333f2569afa938290d9a'), c", + "from tt_depthpro2.server.app import load_config as L\nfor bad in ({'DEPTHPRO2_SIZE': 'XL'}, {'DEPTHPRO2_RESOLUTIONS': '480x'}, {'DEPTHPRO2_WINDOW': '17'}, {'DEPTHPRO2_OVERLAP': '16'}, {'DEPTHPRO2_VIDEO_MODES': 'live'}, {'DEPTHPRO2_KV_STREAMS': '0'}, {'DEPTHPRO2_ENGINE': 'dec=gpu'}, {'TT_MESH_SHAPE': '1x2'}):\n try:\n L(bad)\n except RuntimeError:\n continue\n raise AssertionError(bad)", + "from tt_depthpro2.config import WEIGHTS; assert WEIGHTS == {'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')}", + "import tt_depthpro2.api, tt_depthpro2.cpu_engine, tt_depthpro2.streaming, tt_depthpro2.reference.model as R; assert R.SIZES['H'].swiglu and tt_depthpro2.api.plan_buffered_clips(10, 4, 1) == [4, 4, 4]", + "from tt_depthpro2.tt.model import DepthPro2Device as D, trace_region_bytes, planned_frames, kv_state_bytes; import inspect; p = inspect.signature(D).parameters; assert D.supports_kv_cache and all(k in p for k in ('fov_shapes', 'clip_lengths', 'precision', 'kv_cache', 'kv_streams')) and hasattr(D, 'inverse_depth_step') and trace_region_bytes('L', [(480, 640), (640, 480)], [1, 16], kv_cache=True) > (64 << 20)", + "import importlib.util; from pathlib import Path; d = Path('/opt/tt-metal/tt_depthpro2/tt'); assert all((d / f'mk_enc/kernels/me_{r}.cpp').is_file() and (d / f'mk_dec/kernels/md_{r}.cpp').is_file() for r in ('brisc', 'ncrisc', 'trisc')) and all(importlib.util.find_spec(f'tt_depthpro2.tt.{m}') for m in ('mk_enc', 'mk_fov', 'mk_dec'))", + "from pathlib import Path; d = Path('/opt/tt-metal/tt_depthpro2/tt'); n = {p.name for p in (d / 'mk_enc' / 'kernels').iterdir()}; m = {p.name for p in (d / 'mk_dec' / 'kernels').iterdir()}; assert {'me_brisc.cpp', 'me_ncrisc.cpp', 'me_trisc.cpp', 'me_defs.hpp', 'me_dm.hpp'} <= n and {'md_brisc.cpp', 'md_ncrisc.cpp', 'md_trisc.cpp', 'md_defs.hpp'} <= m, (n, m)", + "from tt_depthpro2.config import DEFAULT_ENGINE, resolve_config; assert DEFAULT_ENGINE == {'enc': 'mk', 'dec': 'mk', 'fov': 'mk'} and resolve_config(env={}).engine == DEFAULT_ENGINE and resolve_config(env={'DEPTHPRO2_ENGINE': 'dec=ttnn'}).engine == {'enc': 'mk', 'dec': 'ttnn', 'fov': 'mk'}", + "import hashlib, json; from pathlib import Path; d = Path('/opt/tt-metal/tt_depthpro2/samples/kropa_street'); assert hashlib.sha256((d / 'image.jpg').read_bytes()).hexdigest() == 'dee4f3aafb7a1724d251e9af56ad9cd5eebbb95289ff63f4cdc1a2e0609445ae' and (d / 'PROVENANCE.md').is_file() and all(json.loads((d / f'reference.{s}.json').read_text())['size'] == s and (d / f'reference.{s}.npy').is_file() for s in 'SBLH')", + "from pathlib import Path; d = Path('/opt/tt-metal/tt_depthpro2/licenses'); assert 'Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement.' in (d / 'NOTICE.md').read_text() and 'Research Purposes' in (d / 'APPLE_MLR_MODEL_LICENSE.txt').read_text() and (d / 'APPLE_SOFTWARE_LICENSE.txt').read_text().startswith('Copyright (C) 2026 Apple Inc.')", + "from pathlib import Path; assert all(Path('/opt/tt-metal', p).is_file() for p in ('tt_depthpro2/server/smoke_test.py', 'tt_depthpro2/server/client.py', 'scripts/bench.py', 'scripts/container_smoke.sh', 'scripts/make_sample_reference.py', 'scripts/make_demo.py', 'scripts/device_server_smoke.py'))", + "import numpy; assert int(numpy.__version__.split('.')[0]) < 2, numpy.__version__", + "import safetensors, huggingface_hub, PIL, fastapi, uvicorn; assert (safetensors.__version__, PIL.__version__) == ('0.8.0', '12.3.0'), (safetensors.__version__, PIL.__version__)", + "import torch; assert torch.__version__.startswith('2.11.0'), torch.__version__", + "import ttnn; assert all(hasattr(ttnn, a) for a in ('DispatchCoreConfig', 'begin_trace_capture', 'end_trace_capture', 'execute_trace', 'release_trace', 'copy_host_to_device_tensor', 'generic_op'))" + ], + "built": { + "image": "tt-model/depthpro2:8405af31ce62", + "repo": "changh95/DepthPro2", + "tt_model_version": "0.1.0", + "created_at": "2026-11-29T05:07:03+00:00", + "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 + }, + "code_sha256": "bc0132ce79669bfc545af9782cb4e5f8fe2a8edb0d9acb2f749485c4fd0fc5c3", + "image_digest": "sha256:8405af31ce627ee3d18eb7e0bf0aa8c4d8c2e8625851e733d98a8bfdbc1cfeba" + }, + "card": { + "description": "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).", + "attribution": "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.", + "prerequisites": "- 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\n- 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\n", + "quickstart": "Send the sample image shipped in this repo (a 640 x 480 CC0 street photo) to `/predict` (JSON) and to\n`/predict_png` (raw file in, 16-bit depth PNG out), on the port `tt serve` reported:\n\n```bash\ncurl -sLO https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/samples/kropa_street/image.jpg\npython3 -c \"import base64, json; json.dump({'image': base64.b64encode(open('image.jpg', 'rb').read()).decode()}, open('req.json', 'w'))\"\ncurl -s localhost:20000/predict -H 'Content-Type: application/json' -d @req.json -o resp.json\ncurl -s localhost:20000/predict_png --data-binary @image.jpg -o depth16.png # uint16 = round(depth_m * 1000)\npython3 -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'])\"\n```\n", + "architecture": null, + "status": null, + "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.", + "out_of_scope_use": null, + "usage": "`POST /predict` takes one base64 image and returns its depth map; `POST /predict_png` takes the raw image file and\nreturns a 16-bit depth PNG; `POST /predict_video` takes the frames of a clip or video and returns one depth map\nper frame. `GET /health` reports readiness, `GET /info` the weights and their commits, the device, the engines,\nthe configuration and the limits, `GET /config` the configuration only; `GET /v1/models` is a stub, not a chat\nAPI.\n\n| request field (`POST /predict`) | meaning |\n| --- | --- |\n| `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 |\n| `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 |\n| `use_exif` (optional) | `true` (default): use the EXIF focal length when `f_px` is not given |\n| `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) |\n| `include_inverse_depth` (optional) | also return the focal-normalized inverse depth |\n| `png_scale` (optional) | `png16`: units per metre, default 1000 (millimetres; 65.535 m saturates) |\n\n`POST /predict_png` takes the image file as the body and the query parameters `f_px`, `png_scale` and `use_exif`;\nthe focal length, the statistics and the timing come back in `X-Focal-Length-Px`, `X-Stats-M`, `X-Timing-Ms` and\nfurther `X-*` headers.\n\n| request field (`POST /predict_video`) | meaning |\n| --- | --- |\n| `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 |\n| `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) |\n| `stream` (optional) | `{\"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` returns the rest and closes it; one unbuffered stream at a time by default |\n| `f_px`, `window`, `overlap`, `output_format`, `include_inverse_depth` (optional) | as above; `window` / `overlap` at most the server's |\n\nResponse of `/predict` for the sample image as served on the p150 (depth data elided, values rounded, profile\n`l`):\n\n```json\n{\"model\": \"depthpro2\", \"size\": \"L\", \"frames\": 1, \"input_size\": [480, 640], \"bucket\": [480, 640],\n \"device_size\": [480, 640], \"resized\": false, \"focallength_px\": 490.04, \"focal_source\": \"fov\",\n \"fov_deg\": [[65.85, 52.19]],\n \"depth\": {\"format\": \"npy\", \"dtype\": \"float16\", \"shape\": [480, 640], \"data\": \"...\", \"units\": \"m\"},\n \"stats_m\": {\"pixels\": 307200, \"infinite_pixels\": 32165, \"min\": 1.43, \"p05\": 1.68, \"median\": 6.97,\n \"p95\": 29.5, \"max\": 28666.4},\n \"timing_ms\": {\"decode\": \"...\", \"preprocess\": \"...\", \"device\": \"...\", \"fov\": \"...\", \"postprocess\": \"...\",\n \"encode\": \"...\", \"total\": \"...\"}}\n```\n\n- `depth` is metres along the optical axis at the input size; `inf` (`infinite_pixels`) marks sky, where the\n network's inverse depth is 0. Decode with `np.load(io.BytesIO(base64.b64decode(depth[\"data\"])))`; values\n above 65504 m read as `inf` in the float16 encoding (`npy32` keeps them).\n- `focallength_px` is in input pixels; `focal_source` is `request`, `exif` or `fov`. `fov_deg` is the estimated\n horizontal and vertical field of view per frame.\n- An input of exactly a bucket's size runs natively (`resized: false`); any other size is resized to the bucket\n of the nearest aspect ratio and back (`resized: true`). `/info` lists the buckets.\n- `timing_ms` is measured in the server: decoding, pre-processing, the device run, the focal-length estimate,\n post-processing and response encoding.\n- Errors: HTTP 400 with the reason for an image that cannot be decoded or is out of the size range, a\n non-positive `f_px`, frames of different sizes, a clip length the device programs were not built for, or a\n disabled video mode; 422 for an unknown field or a value of the wrong type; 429 when too many video streams are\n open; 503 while the server starts; 500 with the exception text on a device failure.\n- A Python API with the same outputs (`tt_depthpro2.DepthPro2`: `infer`, `infer_clip`, `infer_video`, `stream`)\n is described in [`code/PYTHON.md`](code/PYTHON.md); it needs a tt-metal build with the two patches in\n [`patches/`](patches/).\n\n### Configuration\n\nThe server builds its device programs for one configuration when it starts; change it with environment variables\nin the container's launch command (`tt-model serve --print` prints it) and start it again. `GET /config` reports\nit.\n\n| item | environment variable | values | default |\n| --- | --- | --- | --- |\n| model size | `DEPTHPRO2_SIZE` (the serve profiles set it) | `S`, `B`, `L`, `H` | `L` (profile `l`) |\n| 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` |\n| video clip length | `DEPTHPRO2_WINDOW` | 1 to 16 | 16 |\n| buffered overlap | `DEPTHPRO2_OVERLAP` | 0 to window - 1 | 4 |\n| further clip lengths | `DEPTHPRO2_CLIP_LENGTHS` | `auto` (1 and the window), `all`, or a list | `auto` |\n| focal-length estimator | `DEPTHPRO2_FOV` | 1 / 0 | 1 |\n| video modes | `DEPTHPRO2_VIDEO_MODES` | `buffered`, `unbuffered`, both, or `auto` | `auto`: both when the key-value caches fit 4 GiB of device memory |\n| unbuffered streams open at once | `DEPTHPRO2_KV_STREAMS` | 1 to 8 (one cache per bucket each) | 1 |\n| 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` |\n\nEvery bucket adds device programs and their start-up time; any clip length up to the window runs on the window's\nprogram. The unbuffered key-value caches take device memory per bucket and stream (window 16):\n\n| size | per 480 x 640 bucket | default (2 buckets, 1 stream) | per 1080 x 1920 bucket |\n| --- | --- | --- | --- |\n| S | 108 MiB | 217 MiB | 720 MiB |\n| B | 217 MiB | 434 MiB | 1.41 GiB |\n| L | 578 MiB | 1.13 GiB | 3.75 GiB |\n| H+ | 993 MiB | 1.94 GiB | 6.45 GiB (above the `auto` budget: buffered only) |\n", + "performance": "Agreement with Apple's own float32 code on the CPU (same weights and inputs) of the shipped engines (encoder,\ndecoder and focal-estimator megakernels), per size, with Apple's own bfloat16 run (its default on GPUs) in\nparentheses:\n\n| eval | S | B | L | H+ | frames |\n| --- | --- | --- | --- | --- | --- |\n| Inverse depth PCC, a 480 x 640 image | 0.999996 | 0.999997 | 0.999999 | 0.999999 | 1 |\n| Depth AbsRel, a 480 x 640 image | 0.0035 (0.0039) | 0.0025 (0.0021) | 0.0016 (0.0035) | 0.0024 (0.0016) | 1 |\n| 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 |\n| 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 |\n| 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 |\n| 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 |\n| 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 |\n\nAbsRel is the mean relative depth error over the pixels within 100 times the nearest distance, with Apple's\nfocal length. Apple's float32 output exists for every case except the 375 x 500 image at L and H+, which is\ncompared with this package's float32 CPU reference (equal to Apple's float32 code to a relative error of 1e-5,\nthis image included); the numbers in parentheses are Apple's own code run in bfloat16 on the same inputs. The\nfocal-length estimator is shared by every size. [1] L's prediction for this image is nearly flat (its inverse\ndepth varies by about 6 % across the image, against 33-42 % for the other sizes), so its PCC is low (0.995 here,\nagainst 0.9995 for Apple's own bfloat16 run), but its depth AbsRel (0.0035) is within Apple's own bfloat16 AbsRel\n(0.0052).\n\nDeterminism: the encoder and focal-estimator megakernels gave bit-identical outputs over 10 launches and 1000\ntrace replays at each of 10 shapes (480 x 640 with 1, 4 and 16 frames, 736 x 1280, the focal-estimator trunk),\nwith no hang; the decoder megakernel over 22 launches and 1000 trace replays at each of 15 configurations (every\nsize 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+, with\n1 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 640\nwith 1, 4 and 16 frames, 736 x 1280 and 1088 x 1920).\n\n| speed (batch 1, warm) | input | S | B | L | H+ |\n| --- | --- | --- | --- | --- | --- |\n| 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 |\n| 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 |\n| Device time, focal-estimator megakernel: 1 / 4 frames | 480 x 640 | 5.7 / 18.3 ms | same | same | same |\n| Device time per image (encoder + decoder) | 480 x 640 | 5.7 ms | 12.0 ms | 30.2 ms | 50.6 ms |\n| 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) |\n| Served `POST /predict`, server `timing_ms.total` (focal estimated) | the sample, 640 x 480 JPEG | 39 ms | 44 ms | 64 ms | 84 ms |\n| Served `POST /predict`, client round trip on loopback | the sample | 58 ms | 63 ms | 82 ms | 102 ms |\n| 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 |\n| 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 |\n| 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 |\n| 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 |\n| 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 |\n\nDevice times: traced replays back to back on one p150 (each megakernel from its release benchmark). Served rows:\nrequests to the HTTP server of this package with its default configuration (buckets 480 x 640 and 640 x 480,\nwindow 16, unbuffered video on) on the same p150 in an 8-vCPU AMD EPYC-Rome host\n(`code/scripts/device_server_smoke.py`: 10 requests of the sample, one of each video request; the video requests\nreturned float32 depth and inverse depth for every frame, which is part of their time). A served request adds\nimage decoding, resizing, the focal estimate when no `f_px` is sent and the response encoding on the host CPU.\nStart-up: the server's own \"ready in\" time in the container started by `tt serve`, per profile; the first start\ncompiles the device kernels into the container's kernel cache, which `tt serve` keeps for later starts.\n", + "limitations": "- Research use only: Apple's licence allows the weights, and models derived from them such as this package, to be\n used exclusively for non-commercial scientific research; no commercial use, product development or use in a\n commercial product or service. Not for safety-critical uses (driving, robot control, medical or industrial\n measurement): the depth is an estimate from one camera, unvalidated for such uses, on the device and on Apple's\n code alike.\n- Inputs of a size that is not a configured bucket are resized to the bucket of the nearest aspect ratio and the\n outputs are resized back, so their results approximate what the network gives at the input's own size (an\n aspect ratio far from every bucket is stretched, and a small image upscaled to a larger bucket changes the\n focal-length estimate). Configure your camera's native resolution as a bucket (`DEPTHPRO2_RESOLUTIONS`) for the\n most faithful results.\n- Accuracy outside the gate images: of 16 held-out cases (four inputs at every size, scored against Apple's\n float32 output with the same gates), 14 pass. Both misses are on one 480 x 640 photo (Apple's `images.jpg`).\n L sees that scene as nearly flat (its inverse depth varies by about 15 % across the image) and reaches an\n inverse-depth PCC of 0.998, below the 0.999 gate, where Apple's own bfloat16 run reaches 0.9993; its depth\n AbsRel (0.0060) is 1.1 times Apple's bfloat16 error, within the 2x target. S's depth AbsRel on that photo is\n 0.027, 2.05 times Apple's bfloat16 error (0.0133), just over the 2x target. Near-flat scenes (for PCC) and S's\n depth error on sensitive scenes are the weakest points of this port. The all-tt-nn engine\n (`DEPTHPRO2_ENGINE=ttnn`) gives S a lower depth error on that photo (0.022, 1.7 times Apple's bfloat16 error)\n at about 2.8 times the device time per image.\n- The resolution buckets and the video window are fixed when the server starts. A clip shorter than the window\n runs on the window's device program and takes as long as a full window.\n- Buffered video returns a frame only once its clip is predicted, so it lags the input by up to a window;\n unbuffered video returns each frame at once but sees only earlier frames, and one unbuffered stream is open at\n a time by default (more need `DEPTHPRO2_KV_STREAMS`; a stream beyond it is refused with HTTP 429). The\n unbuffered frame-by-frame steps run the encoder in tt-nn operations (the encoder megakernel has no key-value\n cache path), so they are slower per frame than an image.\n- The tt-nn decoder remains selectable (`DEPTHPRO2_ENGINE=dec=ttnn`), as does each stage's tt-nn implementation.\n- The tt-nn encoder (the unbuffered steps, and `enc=ttnn`) uses tt-nn's scaled-dot-product attention, which\n returned wrong rows when its batch x heads exceeded 24 (tt-nn encoder clips of 16 frames at 480 x 640 or of 4\n frames for H+); the package runs those attentions in tt-nn's windowed mode, which is correct and gives the same\n results.\n- Batch 1; requests are served one at a time. One p150 only: the image runs device dispatch on the chip's Ethernet\n cores, so multi-chip meshes are not supported.\n- Precision: bfloat16 weights and activations on the device with float32 accumulation, residual streams,\n normalisation statistics and positional rotations, against Apple's float32 reference (Apple evaluates in\n bfloat16 on GPUs); Expected performance gives the measured agreement.\n- All four sizes' weights are downloaded whichever profile is served. The focal length comes from the image's EXIF\n data when present (35 mm-equivalent focal length), which can be wrong for cropped or digitally zoomed images:\n pass `f_px` or `use_exif: false` then.\n", + "risks": null, + "licensing": "- Weights (not redistributed here; `tt serve` downloads them from Apple's repositories at these commits):\n [apple/DepthPro2-focal](https://huggingface.co/apple/DepthPro2-focal) `622659d4`,\n [apple/DepthPro2-S](https://huggingface.co/apple/DepthPro2-S) `903a1c1a`,\n [apple/DepthPro2-B](https://huggingface.co/apple/DepthPro2-B) `85e67fdf`,\n [apple/DepthPro2-L](https://huggingface.co/apple/DepthPro2-L) `849dc546`,\n [apple/DepthPro2-H](https://huggingface.co/apple/DepthPro2-H) `68426c78`, under the\n [Apple Machine Learning Research Model License Agreement](https://huggingface.co/apple/DepthPro2/blob/main/LICENSE):\n **research purposes only**. Apple Machine Learning Research Model is licensed under the Apple Machine Learning\n Research Model License Agreement. A copy of the agreement and the notices are in\n [`code/tt_depthpro2/licenses/`](code/tt_depthpro2/licenses/NOTICE.md).\n- This package is a model derivative of Depth Pro 2 and is identified as such. Its modifications: the inference\n code is re-implemented (the network and the pre- and post-processing written anew; the video streaming logic\n follows the structure of Apple's `streaming.py`, see below); on the device the network runs in bfloat16 in\n tt-nn operations and custom device kernels; inputs are resized to fixed resolution buckets. The weights are\n loaded unmodified. Apple's name is used only to identify the original model; Apple does not endorse this\n package.\n- The video streaming logic (`code/tt_depthpro2/streaming.py`) follows the structure of Apple's `streaming.py`\n from [apple-aiml-research/ml-depth-pro-2](https://github.com/apple-aiml-research/ml-depth-pro-2) (Copyright (C)\n 2026 Apple Inc.), used under Apple's software licence, a copy of which is\n [`code/tt_depthpro2/licenses/APPLE_SOFTWARE_LICENSE.txt`](code/tt_depthpro2/licenses/APPLE_SOFTWARE_LICENSE.txt).\n- Port, server and scripts (`code/`, except as noted above) and the tt-metal patches in [`patches/`](patches/):\n Apache-2.0.\n- Sample `code/tt_depthpro2/samples/kropa_street/image.jpg`: \"Kropa, cobblestone side street 01\" by Ajznponar,\n [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Kropa,_cobblestone_side_street_01.jpg), CC0 1.0\n (public domain dedication), resized to 640 x 480 without its EXIF data; the `reference.*` files next to it hold\n this package's float32 CPU outputs for it.\n", + "related": "- [changh95/depth-anything-3-p150](https://huggingface.co/changh95/depth-anything-3-p150): Depth Anything 3 metric depth on p150.\n", + "license": { + "id": "other", + "name": "Apple AMLR", + "link": "https://huggingface.co/apple/DepthPro2/blob/main/LICENSE" + }, + "pipeline_tag": "depth-estimation", + "base_model": [ + "apple/DepthPro2-L", + "apple/DepthPro2-S", + "apple/DepthPro2-B", + "apple/DepthPro2-H", + "apple/DepthPro2-focal" + ] + } + } +} \ No newline at end of file