Python API: warm-up so the first real call is fast (warmup_variants, model.warmup()), quiet logs, install extras
Browse filesfrom_pretrained() now warms up the common per-request variants with dummy inputs (device and host), so the first real call is within about 10% of later calls (independently verified in fresh processes; outputs bit-identical; steady-state latency unchanged). Adds model.warmup(...) for other variants, verbose=False by default, and documents the [server,test] extras and repo-root paths. tt-model.yaml and SERVING.md are unchanged.
- README.md +5 -1
- code/PYTHON.md +154 -10
- code/examples/quickstart.py +2 -0
- code/gaze_lle/api.py +261 -24
- code/gaze_lle/tests/test_api_host.py +108 -0
- code/gaze_lle/tests/test_api_warmup_device.py +125 -0
- code/gaze_lle/tt/custom_ops.py +3 -0
- code/scripts/first_call_bench.py +139 -0
README.md
CHANGED
|
@@ -33,7 +33,8 @@ Prerequisite: a Python environment with a built tt-metal / `ttnn` at tt-metal `8
|
|
| 33 |
|
| 34 |
```bash
|
| 35 |
hf download changh95/gaze-lle-p150 --exclude "image/*" --local-dir gaze-lle-p150 && cd gaze-lle-p150
|
| 36 |
-
pip install -e code/
|
|
|
|
| 37 |
```
|
| 38 |
|
| 39 |
```python
|
|
@@ -49,8 +50,11 @@ result.heatmap # torch (N, 64, 64) heatmaps over the wh
|
|
| 49 |
visualize("media/source_1.png", result).save("gaze.png")
|
| 50 |
```
|
| 51 |
|
|
|
|
| 52 |
- `from_pretrained` downloads the pinned weights [`changh95/gaze-lle-weights`](https://huggingface.co/changh95/gaze-lle-weights) to the HF cache. It opens the chip with ETH dispatch and the 12×10 grid.
|
| 53 |
- It captures the metal traces for 1, 2, 3, 4, 6, 8 and 10 heads and runs 2 warm-up forwards. A cold start takes approximately 1 minute.
|
|
|
|
|
|
|
| 54 |
- Without the ETH-dispatch patch, the model uses the default dispatch and shows a `RuntimeWarning`. The results are identical, but the calls are slower.
|
| 55 |
- The `with` block releases the traces, the weights and the chip at the end. You can also call `model.close()`.
|
| 56 |
- The output is identical to the HTTP `/predict` response for the same image and boxes (tested bit for bit).
|
|
|
|
| 33 |
|
| 34 |
```bash
|
| 35 |
hf download changh95/gaze-lle-p150 --exclude "image/*" --local-dir gaze-lle-p150 && cd gaze-lle-p150
|
| 36 |
+
pip install -e code/ # the Python API only
|
| 37 |
+
pip install -e "code/[server,test]" # also the HTTP server (fastapi, uvicorn, pyspng, orjson) and the tests (pytest, httpx)
|
| 38 |
```
|
| 39 |
|
| 40 |
```python
|
|
|
|
| 50 |
visualize("media/source_1.png", result).save("gaze.png")
|
| 51 |
```
|
| 52 |
|
| 53 |
+
- The relative path `media/source_1.png` is correct when the current directory is the model repo root (`gaze-lle-p150`). From a different directory, use the full path.
|
| 54 |
- `from_pretrained` downloads the pinned weights [`changh95/gaze-lle-weights`](https://huggingface.co/changh95/gaze-lle-weights) to the HF cache. It opens the chip with ETH dispatch and the 12×10 grid.
|
| 55 |
- It captures the metal traces for 1, 2, 3, 4, 6, 8 and 10 heads and runs 2 warm-up forwards. A cold start takes approximately 1 minute.
|
| 56 |
+
- `from_pretrained()` prepares all head counts from 1 to 10 and all input types (array, PIL image, PNG or JPEG file, float array, batch). Thus, the first call is as fast as the next calls. The start-up time is approximately 5 s (approximately 1 min on the first run, which compiles the kernels).
|
| 57 |
+
- To prepare more head counts, use `warmup_variants="all"` or `model.warmup(heads=[11])`. Use `max_heads` of 11 or less.
|
| 58 |
- Without the ETH-dispatch patch, the model uses the default dispatch and shows a `RuntimeWarning`. The results are identical, but the calls are slower.
|
| 59 |
- The `with` block releases the traces, the weights and the chip at the end. You can also call `model.close()`.
|
| 60 |
- The output is identical to the HTTP `/predict` response for the same image and boxes (tested bit for bit).
|
code/PYTHON.md
CHANGED
|
@@ -10,9 +10,20 @@ The package needs an environment that already has a built tt-metal (`import ttnn
|
|
| 10 |
tt-metal, and it uses the torch and numpy of that environment.
|
| 11 |
|
| 12 |
```bash
|
| 13 |
-
pip install -e code/
|
|
|
|
| 14 |
```
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
The weights (`changh95/gaze-lle-weights`, pinned revision `f83e53f0`) download to the HF cache on first use.
|
| 17 |
|
| 18 |
## Quickstart
|
|
@@ -20,7 +31,7 @@ The weights (`changh95/gaze-lle-weights`, pinned revision `f83e53f0`) download t
|
|
| 20 |
```python
|
| 21 |
from gaze_lle import GazeLLE, visualize
|
| 22 |
|
| 23 |
-
with GazeLLE.from_pretrained() as model: # device 0; loads weights, captures traces
|
| 24 |
result = model("media/source_1.png", # path, PIL image, numpy or torch array
|
| 25 |
[[116, 28, 176, 104], [269, 37, 301, 81]], # one head box per person
|
| 26 |
bbox_format="pixels") # default "normalized" = fractions of W/H
|
|
@@ -30,14 +41,20 @@ print(result.inout) # (N,) probability that the gaze target is inside the f
|
|
| 30 |
visualize("media/source_1.png", result).save("gaze.png")
|
| 31 |
```
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
## `GazeLLE.from_pretrained(...)`
|
| 37 |
|
| 38 |
```python
|
| 39 |
GazeLLE.from_pretrained(repo_id="changh95/gaze-lle-weights", *, revision="f83e53f0...", weights_dir=None,
|
| 40 |
-
device=None, device_id=0, dispatch="auto", max_heads=10, warmup=True
|
|
|
|
| 41 |
```
|
| 42 |
|
| 43 |
| argument | default | meaning |
|
|
@@ -48,7 +65,9 @@ GazeLLE.from_pretrained(repo_id="changh95/gaze-lle-weights", *, revision="f83e53
|
|
| 48 |
| `device_id` | 0 | device to open when `device` is None |
|
| 49 |
| `dispatch` | `"auto"` | `"auto"`: ETH dispatch and a 12x10 grid when the tt-metal has the Blackhole ETH-dispatch patch (the configuration of the published numbers), else the default dispatch with a `RuntimeWarning`. `"eth"` or `"default"` to force one. |
|
| 50 |
| `max_heads` | 10 | most head boxes per image. Traces are captured for the head-count buckets 1, 2, 3, 4, 6, 8, 10 that are <= `max_heads`; N boxes run in the smallest bucket >= N. |
|
| 51 |
-
| `warmup` | True |
|
|
|
|
|
|
|
| 52 |
|
| 53 |
The result is identical with ETH dispatch and with the default dispatch (tested bit for bit); only the time changes.
|
| 54 |
|
|
@@ -87,8 +106,8 @@ the image: `torch.nn.functional.interpolate(result.heatmap[None], size=(H, W), m
|
|
| 87 |
| call | what it does |
|
| 88 |
|---|---|
|
| 89 |
| `model.predict_batch(images, bboxes, *, bbox_format="normalized", num_workers=2)` | many images. The device runs one image at a time (same numbers as single calls); host threads decode and resize the next images while the device works. `bboxes[i]` is the box list of `images[i]`. |
|
| 90 |
-
| `model.warmup(iters=2)` |
|
| 91 |
-
| `model.info()` | dispatch, grid, `max_heads`, captured trace buckets
|
| 92 |
| `model.close()` / `with ... as model:` | release the traces and on-device weights; close the device if `from_pretrained` opened it. Calling it again does nothing. |
|
| 93 |
| `gaze_lle.open_device(device_id=0, dispatch="auto")` | open a device the same way as `from_pretrained`, for `from_pretrained(device=...)` |
|
| 94 |
| `gaze_lle.visualize(image, result, inout_thresh=0.5)` | PIL overlay: all head boxes; heatmap and gaze line for heads with `inout >= inout_thresh` (as upstream `visualize_all`) |
|
|
@@ -107,6 +126,118 @@ Calls are thread safe: one device call runs at a time.
|
|
| 107 |
Two runs of `test_api_device.py` (300 interleaved calls each, chip 2, shared host). The API adds 0.03-0.05 ms (median) of host work (box checks, result object) to the bare model call; `gaze_xy` and `score` are computed when you first read them. For other image
|
| 108 |
sizes, the resize to 448x448 on the host adds time; give a 448x448 uint8 array to skip it.
|
| 109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
## Environment
|
| 111 |
|
| 112 |
* Device knobs (`TT_FUSED*`) are read from the environment when the model is built. Their defaults are the served
|
|
@@ -116,7 +247,20 @@ sizes, the resize to 448x448 on the host adds time; give a 448x448 uint8 array t
|
|
| 116 |
|
| 117 |
## Tests
|
| 118 |
|
|
|
|
|
|
|
| 119 |
```bash
|
| 120 |
-
TT_VISIBLE_DEVICES=none
|
| 121 |
-
python -m pytest code/gaze_lle/tests/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
tt-metal, and it uses the torch and numpy of that environment.
|
| 11 |
|
| 12 |
```bash
|
| 13 |
+
pip install -e code/ # from the model repo root: the Python API only
|
| 14 |
+
pip install -e "code/[server,test]" # also the HTTP server (fastapi, uvicorn, pyspng, orjson) and the tests (pytest, httpx)
|
| 15 |
```
|
| 16 |
|
| 17 |
+
In this repo's model venv, use its pip with the shared constraints:
|
| 18 |
+
`.venv/bin/python -m pip install -e "code/[server,test]" -c .venv/shared-constraints.txt`.
|
| 19 |
+
|
| 20 |
+
| you want to run | extras you need |
|
| 21 |
+
|---|---|
|
| 22 |
+
| the Python API (`from gaze_lle import GazeLLE`) | none |
|
| 23 |
+
| the HTTP server (`gaze_lle.server.app`) | `server` |
|
| 24 |
+
| the host tests (no device) | `test` and `server` (`test_api_host.py` and `test_server_host.py` compare the API with the server code) |
|
| 25 |
+
| the device tests | `test` and `server` |
|
| 26 |
+
|
| 27 |
The weights (`changh95/gaze-lle-weights`, pinned revision `f83e53f0`) download to the HF cache on first use.
|
| 28 |
|
| 29 |
## Quickstart
|
|
|
|
| 31 |
```python
|
| 32 |
from gaze_lle import GazeLLE, visualize
|
| 33 |
|
| 34 |
+
with GazeLLE.from_pretrained() as model: # device 0; loads weights, captures traces, warms up
|
| 35 |
result = model("media/source_1.png", # path, PIL image, numpy or torch array
|
| 36 |
[[116, 28, 176, 104], [269, 37, 301, 81]], # one head box per person
|
| 37 |
bbox_format="pixels") # default "normalized" = fractions of W/H
|
|
|
|
| 41 |
visualize("media/source_1.png", result).save("gaze.png")
|
| 42 |
```
|
| 43 |
|
| 44 |
+
The relative path `media/source_1.png` assumes that the current directory is the model repo root. From another
|
| 45 |
+
directory, give the full path. `python code/examples/quickstart.py` runs this snippet on the demo image (it finds the
|
| 46 |
+
image relative to its own file, so it works from any directory) and writes `gaze_quickstart.png` and
|
| 47 |
+
`gaze_quickstart.json` in the current directory.
|
| 48 |
+
|
| 49 |
+
`from_pretrained` takes about 5 s when the tt-metal kernel cache is warm and about 1 min the first time (kernel
|
| 50 |
+
compile). When it returns, the first real call is as fast as the later calls (see [Warm-up](#warm-up)).
|
| 51 |
|
| 52 |
## `GazeLLE.from_pretrained(...)`
|
| 53 |
|
| 54 |
```python
|
| 55 |
GazeLLE.from_pretrained(repo_id="changh95/gaze-lle-weights", *, revision="f83e53f0...", weights_dir=None,
|
| 56 |
+
device=None, device_id=0, dispatch="auto", max_heads=10, warmup=True,
|
| 57 |
+
warmup_variants="default", verbose=False) -> GazeLLE
|
| 58 |
```
|
| 59 |
|
| 60 |
| argument | default | meaning |
|
|
|
|
| 65 |
| `device_id` | 0 | device to open when `device` is None |
|
| 66 |
| `dispatch` | `"auto"` | `"auto"`: ETH dispatch and a 12x10 grid when the tt-metal has the Blackhole ETH-dispatch patch (the configuration of the published numbers), else the default dispatch with a `RuntimeWarning`. `"eth"` or `"default"` to force one. |
|
| 67 |
| `max_heads` | 10 | most head boxes per image. Traces are captured for the head-count buckets 1, 2, 3, 4, 6, 8, 10 that are <= `max_heads`; N boxes run in the smallest bucket >= N. |
|
| 68 |
+
| `warmup` | True | False skips all warm-up (same as `warmup_variants=None`). The first call of each head bucket then captures its trace (about 0.3 s, or seconds when kernels compile). |
|
| 69 |
+
| `warmup_variants` | `"default"` | the variants to prepare now, so that their first real call is fast. See [Warm-up](#warm-up). |
|
| 70 |
+
| `verbose` | False | False: a quiet console. tt-metal and UMD log only errors (`TT_LOGGER_LEVEL=error`), and ttnn's loguru logs warnings and errors (`LOGURU_LEVEL=WARNING`). The package sets these only if you did not set them and only before the first `import ttnn` (they are read at import). True: tt-metal's normal info log, and `gaze_lle` INFO messages (device open, trace capture and warm-up times) on stderr. |
|
| 71 |
|
| 72 |
The result is identical with ETH dispatch and with the default dispatch (tested bit for bit); only the time changes.
|
| 73 |
|
|
|
|
| 106 |
| call | what it does |
|
| 107 |
|---|---|
|
| 108 |
| `model.predict_batch(images, bboxes, *, bbox_format="normalized", num_workers=2)` | many images. The device runs one image at a time (same numbers as single calls); host threads decode and resize the next images while the device works. `bboxes[i]` is the box list of `images[i]`. |
|
| 109 |
+
| `model.warmup(heads="buckets", inputs="all", iters=2)` | prepare more variants later (see [Warm-up](#warm-up)). Idempotent: warm variants are skipped. Returns `model.warmup_report` (seconds per variant). |
|
| 110 |
+
| `model.info()` | dispatch, grid, `max_heads`, captured trace buckets, device knobs, warm head buckets and input paths, `warmup_report` |
|
| 111 |
| `model.close()` / `with ... as model:` | release the traces and on-device weights; close the device if `from_pretrained` opened it. Calling it again does nothing. |
|
| 112 |
| `gaze_lle.open_device(device_id=0, dispatch="auto")` | open a device the same way as `from_pretrained`, for `from_pretrained(device=...)` |
|
| 113 |
| `gaze_lle.visualize(image, result, inout_thresh=0.5)` | PIL overlay: all head boxes; heatmap and gaze line for heads with `inout >= inout_thresh` (as upstream `visualize_all`) |
|
|
|
|
| 126 |
Two runs of `test_api_device.py` (300 interleaved calls each, chip 2, shared host). The API adds 0.03-0.05 ms (median) of host work (box checks, result object) to the bare model call; `gaze_xy` and `score` are computed when you first read them. For other image
|
| 127 |
sizes, the resize to 448x448 on the host adds time; give a 448x448 uint8 array to skip it.
|
| 128 |
|
| 129 |
+
## Warm-up
|
| 130 |
+
|
| 131 |
+
`from_pretrained` prepares the variants that most users hit, so that the FIRST real call is as fast as the later
|
| 132 |
+
calls. It does not compile, capture or allocate anything at your first request, and it does not cache results:
|
| 133 |
+
each call runs the device graph on its own input, and the outputs are bit-identical with and without warm-up.
|
| 134 |
+
|
| 135 |
+
A variant is a property of a call that changes what runs:
|
| 136 |
+
|
| 137 |
+
| variant | kind | what the first call of a new variant costs without warm-up |
|
| 138 |
+
|---|---|---|
|
| 139 |
+
| head count N (1..`max_heads`) | device: N heads run in the trace of the smallest head bucket >= N (buckets 1, 2, 3, 4, 6, 8, 10) | trace capture of the bucket: 0.2-0.3 s (kernels cached), or seconds (kernels compile) |
|
| 140 |
+
| input path: 448x448 uint8 array, PIL image, PNG / JPEG file, float array, `predict_batch` | host only (the device input is always the same uint8 448x448 image) | PIL plug-in imports and first decode / resize / thread start: about 1 ms for the first JPEG call; about 50 ms for the first PNG decode in a process that has not imported ttnn |
|
| 141 |
+
|
| 142 |
+
The image size, `bbox_format` and box positions do not change the device graph.
|
| 143 |
+
|
| 144 |
+
### `warmup_variants`
|
| 145 |
+
|
| 146 |
+
```python
|
| 147 |
+
GazeLLE.from_pretrained() # default: {"heads": "buckets", "inputs": "all"}
|
| 148 |
+
GazeLLE.from_pretrained(warmup_variants={"heads": [1, 3], "inputs": ["file"]}) # less start-up work
|
| 149 |
+
GazeLLE.from_pretrained(max_heads=11, warmup_variants="all") # also N = 11 (its own trace)
|
| 150 |
+
GazeLLE.from_pretrained(warmup_variants=None) # nothing (same as warmup=False)
|
| 151 |
+
model.warmup(heads=[11]) # later; idempotent
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
| key | values | default |
|
| 155 |
+
|---|---|---|
|
| 156 |
+
| `heads` | `"buckets"`: the head buckets <= `max_heads`. They cover every N from 1 to the largest bucket (10). `"all"`: every N from 1 to `max_heads`. An int or a list of ints. `None` or `[]`: none. | `"buckets"` |
|
| 157 |
+
| `inputs` | `"all"`, or some of `"array"` (448x448 uint8 array), `"image"` (PIL image, RGB and RGBA), `"file"` (PNG and JPEG file), `"float"` (float array and CHW tensor), `"batch"` (`predict_batch`). `None` or `[]`: none. | `"all"` |
|
| 158 |
+
|
| 159 |
+
Also accepted: `"default"` / `True` (the default), `"all"` (every N and every input path), `None` / `False` /
|
| 160 |
+
`"none"` (nothing).
|
| 161 |
+
|
| 162 |
+
What warm-up does:
|
| 163 |
+
|
| 164 |
+
1. Captures one trace for each head bucket <= `max_heads` (the same traces as the HTTP server). This step was
|
| 165 |
+
done before this change too.
|
| 166 |
+
2. For each head count, runs 2 real forwards through the public call path (host pre-processing, trace replay,
|
| 167 |
+
readback, output decoding) on a dummy picture with N dummy boxes.
|
| 168 |
+
3. For each input path, runs 1 real call on a dummy 640x480 picture (for `"file"`: a PNG and a JPEG file in a
|
| 169 |
+
temporary directory, for `"image"`: RGB and RGBA).
|
| 170 |
+
4. Runs `gc.collect()`, then one more forward, so that a garbage collection or cold host caches do not fall on
|
| 171 |
+
your first call.
|
| 172 |
+
|
| 173 |
+
The dummy pictures are colour gradients with noise, not zeros, so the decoders and the resize do real work.
|
| 174 |
+
Their outputs are dropped.
|
| 175 |
+
|
| 176 |
+
### Cost (Galaxy Blackhole chip, 12x10 grid, ETH dispatch, kernel cache warm)
|
| 177 |
+
|
| 178 |
+
| step | time | device memory |
|
| 179 |
+
|---|---|---|
|
| 180 |
+
| weights, device open, model build | about 3.2 s | on-device weights |
|
| 181 |
+
| capture 7 bucket traces (1, 2, 3, 4, 6, 8, 10) | about 1.5 s | the trace region and the trace buffers of 7 traces (same as before this change and as the server) |
|
| 182 |
+
| forwards for 7 head buckets | about 0.07 s | none |
|
| 183 |
+
| 5 input paths | about 0.2 s | none |
|
| 184 |
+
| `from_pretrained()` total | 4.7-5.4 s (was 4.4-4.6 s) | |
|
| 185 |
+
|
| 186 |
+
With an empty kernel cache (first run on a machine), `from_pretrained` takes about 55 s because tt-metal compiles
|
| 187 |
+
the kernels. `model.warmup_report` and `model.info()["warmup_report"]` give the measured seconds of each step.
|
| 188 |
+
|
| 189 |
+
### Variants that are not prepared by default
|
| 190 |
+
|
| 191 |
+
* Head counts above 10 (with `max_heads` > 10): no default bucket fits, so the first call with N heads captures a
|
| 192 |
+
trace for exactly N heads: 175 ms (kernels cached) or 5.3 s (kernels compile), then 5.5 ms per call at N = 11.
|
| 193 |
+
To prepare it: `warmup_variants="all"` or `model.warmup(heads=[11])` (0.2 s with cached kernels). Each such
|
| 194 |
+
head count adds one trace to device memory.
|
| 195 |
+
* N >= 12 heads fails in this port: the decoder fc1 program at 12 heads has an L1 circular-buffer clash
|
| 196 |
+
(`TT_THROW: Statically allocated circular buffers ... clash with L1 buffers`). This was so before this change
|
| 197 |
+
too (checked at commit 3ce1d3d). Use `max_heads` <= 11.
|
| 198 |
+
* With `warmup=False` / `warmup_variants=None`: the first call takes 280-310 ms (trace capture) instead of 3-7 ms.
|
| 199 |
+
|
| 200 |
+
### Measured first calls
|
| 201 |
+
|
| 202 |
+
Each row is a FRESH process: `from_pretrained()`, then calls 1, 2 and 10, each with a NEW real picture (repo
|
| 203 |
+
`media/` pictures and their mirror images, never the warm-up input) and new boxes, then 96 more calls. "same
|
| 204 |
+
picture median" is the median of the later calls with the call-1 picture (picture sizes differ, so this is the
|
| 205 |
+
fair reference for call 1). Script: `code/scripts/first_call_bench.py`. Times in ms. Shared host (other jobs ran).
|
| 206 |
+
|
| 207 |
+
| variant | before: `from_pretrained` | call 1 | call 2 | call 10 | same picture median | call 1 / median | after: `from_pretrained` | call 1 | call 2 | call 10 | same picture median | call 1 / median |
|
| 208 |
+
|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
|
| 209 |
+
| 448x448 uint8 array, N=1 | 4.6 s | 3.38 | 3.27 | 3.30 | 3.32 | 1.02 | 5.4 s | 3.37 | 3.28 | 3.30 | 3.37 | 1.00 |
|
| 210 |
+
| 448x448 uint8 array, N=2 | 4.5 s | 3.60 | 3.49 | 3.39 | 3.43 | 1.05 | 5.1 s | 3.58 | 3.49 | 3.45 | 3.45 | 1.04 |
|
| 211 |
+
| 448x448 uint8 array, N=3 | 4.4 s | 3.80 | 3.58 | 3.62 | 3.94 | 0.96 | 4.9 s | 3.75 | 3.74 | 3.56 | 3.60 | 1.04 |
|
| 212 |
+
| 448x448 uint8 array, N=4 | 4.5 s | 3.98 | 3.86 | 3.84 | 3.90 | 1.02 | 6.5 s | 4.04 | 3.98 | 3.83 | 3.99 | 1.01 |
|
| 213 |
+
| 448x448 uint8 array, N=5 (bucket 6) | 4.5 s | 4.28 | 4.17 | 4.17 | 4.21 | 1.02 | 4.9 s | 4.25 | 4.13 | 4.15 | 4.30 | 0.99 |
|
| 214 |
+
| 448x448 uint8 array, N=6 | 4.4 s | 4.28 | 4.13 | 4.12 | 4.11 | 1.04 | 4.8 s | 4.18 | 4.13 | 4.16 | 4.31 | 0.97 |
|
| 215 |
+
| 448x448 uint8 array, N=8 | 4.4 s | 4.64 | 4.73 | 4.50 | 4.59 | 1.01 | 5.0 s | 4.58 | 4.50 | 4.70 | 4.50 | 1.02 |
|
| 216 |
+
| 448x448 uint8 array, N=10 | 4.4 s | 4.96 | 4.85 | 4.91 | 4.90 | 1.01 | 4.7 s | 4.85 | 4.77 | 4.69 | 4.79 | 1.01 |
|
| 217 |
+
| PIL image (resize), N=1 | 4.4 s | 5.39 | 5.99 | 5.77 | 5.07 | 1.06 | 5.1 s | 5.21 | 5.81 | 5.83 | 5.49 | 0.95 |
|
| 218 |
+
| PNG file, N=1 | 4.4 s | 9.41 | 13.32 | 16.45 | 9.22 | 1.02 | 5.1 s | 9.57 | 13.37 | 14.02 | 9.28 | 1.03 |
|
| 219 |
+
| PNG file, N=3 | 4.5 s | 9.83 | 13.56 | 15.48 | 10.38 | 0.95 | 5.3 s | 11.79 | 14.25 | 14.05 | 9.39 | 1.26 * |
|
| 220 |
+
| JPEG file, N=1 | 4.7 s | 6.70 | 7.29 | 7.31 | 5.77 | 1.16 | 4.8 s | 6.99 | 7.70 | 7.78 | 5.85 | 1.19 * |
|
| 221 |
+
| float array, N=1 | 4.3 s | 6.16 | 7.27 | 7.11 | 5.78 | 1.07 | 4.9 s | 6.16 | 7.94 | 7.03 | 5.86 | 1.05 |
|
| 222 |
+
| `predict_batch`, 4 pictures, N=3 | 4.4 s | 18.89 | 19.61 | 20.19 | 19.40 | 0.97 | 5.0 s | 19.12 | 19.44 | 21.16 | 19.79 | 0.97 |
|
| 223 |
+
|
| 224 |
+
\* Host noise: 3 more fresh processes each gave call 1 / median 1.03, 1.07, 1.08 (JPEG) and 1.03, 1.03, 1.10
|
| 225 |
+
(PNG N=3). Without the final forward of step 4, call 1 of the array rows was 0.3-0.4 ms slower (the
|
| 226 |
+
`gc.collect()` leaves the host caches cold).
|
| 227 |
+
|
| 228 |
+
What this shows:
|
| 229 |
+
|
| 230 |
+
* The device side was already warm before this change: `from_pretrained` captured every bucket trace, so each
|
| 231 |
+
head count's first call was within 1-5 % of its median. After the change it is within 0-4 %.
|
| 232 |
+
* The host side: in a process without ttnn, the first PNG decode takes about 50 ms (PIL plug-in imports and first
|
| 233 |
+
decode; measured without a device: 55.7 ms first call, 7.9 ms after the `"file"` warm-up, median 7.8 ms). With
|
| 234 |
+
the API, `import ttnn` already loads PIL's PNG plug-in, so the "before" PNG rows show no such cost; the JPEG
|
| 235 |
+
plug-in is not loaded by ttnn, and the first JPEG call was 1.16x its median before and is 1.03-1.08x now. The
|
| 236 |
+
`"file"` warm-up makes this independent of what other modules import.
|
| 237 |
+
* Outputs: the heatmaps and inout of all 10 measured calls of every row are bit-identical before and after.
|
| 238 |
+
* Steady state: unchanged. `test_api_device.py` after the change: 3.42 / 3.52 / 4.66 ms median at N = 1 / 3 / 10
|
| 239 |
+
(published 3.24 / 3.51 / 4.65 ms).
|
| 240 |
+
|
| 241 |
## Environment
|
| 242 |
|
| 243 |
* Device knobs (`TT_FUSED*`) are read from the environment when the model is built. Their defaults are the served
|
|
|
|
| 247 |
|
| 248 |
## Tests
|
| 249 |
|
| 250 |
+
Install the `test` and `server` extras first (see [Install](#install)). Run the commands from the model repo root.
|
| 251 |
+
|
| 252 |
```bash
|
| 253 |
+
# host only, no device (TT_VISIBLE_DEVICES=none makes the device tests skip themselves)
|
| 254 |
+
TT_VISIBLE_DEVICES=none python -m pytest code/gaze_lle/tests/test_api_host.py -q
|
| 255 |
+
TT_VISIBLE_DEVICES=none python -m pytest code/gaze_lle/tests/test_api_host.py code/gaze_lle/tests/test_server_host.py \
|
| 256 |
+
code/gaze_lle/tests/test_fused_host.py -q # all host tests
|
| 257 |
+
|
| 258 |
+
# one chip
|
| 259 |
+
python -m pytest code/gaze_lle/tests/test_api_device.py -q -s # equality with the server, warm call time
|
| 260 |
+
python -m pytest code/gaze_lle/tests/test_api_warmup_device.py -q -s # first call fast; warm-up keeps outputs
|
| 261 |
```
|
| 262 |
+
|
| 263 |
+
`test_api_warmup_device.py` runs each check in a fresh child process. The first real call of each warmed variant
|
| 264 |
+
(N = 1, 3, 10 on a uint8 array; PNG and JPEG file) must be within `max(1.15 x median, median + 0.5 ms)` of the
|
| 265 |
+
median of the next 30 calls on the same picture, and the outputs with `warmup_variants=None` and `"all"` must be
|
| 266 |
+
bit-identical.
|
code/examples/quickstart.py
CHANGED
|
@@ -5,6 +5,8 @@
|
|
| 5 |
python code/examples/quickstart.py # writes gaze_quickstart.png + gaze_quickstart.json
|
| 6 |
|
| 7 |
Options: --image PATH --bbox x1,y1,x2,y2 (pixels, repeatable) --out PREFIX --device-id N.
|
|
|
|
|
|
|
| 8 |
"""
|
| 9 |
from __future__ import annotations
|
| 10 |
|
|
|
|
| 5 |
python code/examples/quickstart.py # writes gaze_quickstart.png + gaze_quickstart.json
|
| 6 |
|
| 7 |
Options: --image PATH --bbox x1,y1,x2,y2 (pixels, repeatable) --out PREFIX --device-id N.
|
| 8 |
+
The default image is found relative to this file (any working directory works); a relative --image or --out path is
|
| 9 |
+
relative to the current directory.
|
| 10 |
"""
|
| 11 |
from __future__ import annotations
|
| 12 |
|
code/gaze_lle/api.py
CHANGED
|
@@ -3,8 +3,8 @@
|
|
| 3 |
|
| 4 |
from gaze_lle import GazeLLE
|
| 5 |
|
| 6 |
-
with GazeLLE.from_pretrained() as model: # opens device 0, loads weights, captures traces
|
| 7 |
-
result = model("media/source_1.png", [[116, 28, 176, 104]], bbox_format="pixels")
|
| 8 |
print(result.gaze_xy, result.inout) # (N, 2) pixels, (N,) P(target in frame)
|
| 9 |
|
| 10 |
``model(image, bboxes)`` does the same host work as the HTTP server's ``POST /predict`` (RGB, squash to 448x448 with
|
|
@@ -18,7 +18,10 @@ import logging
|
|
| 18 |
import math
|
| 19 |
import os
|
| 20 |
import re
|
|
|
|
|
|
|
| 21 |
import threading
|
|
|
|
| 22 |
import warnings
|
| 23 |
from concurrent.futures import ThreadPoolExecutor
|
| 24 |
from dataclasses import dataclass
|
|
@@ -31,7 +34,8 @@ from PIL import Image
|
|
| 31 |
|
| 32 |
from gaze_lle._paths import tt_metal_home
|
| 33 |
|
| 34 |
-
__all__ = ["GazeLLE", "GazeResult", "open_device", "visualize"
|
|
|
|
| 35 |
|
| 36 |
log = logging.getLogger("gaze_lle")
|
| 37 |
|
|
@@ -50,6 +54,10 @@ IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
|
| 50 |
IMAGENET_STD = (0.229, 0.224, 0.225)
|
| 51 |
WARMUP_BBOX = (0.3, 0.2, 0.6, 0.5)
|
| 52 |
DEFAULT_MAX_HEADS = 10
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
_GRID_ENV = "TT_METAL_CORE_GRID_OVERRIDE_TODEPRECATE"
|
| 54 |
|
| 55 |
ImageLike = Union[str, os.PathLike, Image.Image, np.ndarray, torch.Tensor]
|
|
@@ -262,6 +270,114 @@ def _resolve_weights(repo_id: str, revision: Optional[str], weights_dir: Optiona
|
|
| 262 |
return fetch(DINOV2_FILE), fetch(GAZE_FILE)
|
| 263 |
|
| 264 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
# --------------------------------------------------------------------------------------
|
| 266 |
# Device
|
| 267 |
# --------------------------------------------------------------------------------------
|
|
@@ -353,6 +469,10 @@ class GazeLLE:
|
|
| 353 |
fused = bool(getattr(tt_model, "fused", False))
|
| 354 |
cfg = getattr(tt_model, "fused_cfg", None)
|
| 355 |
self._uint8_input = fused and cfg is not None and getattr(cfg, "input", "") == "raw"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
|
| 357 |
# ------------------------------------------------------------------ construction
|
| 358 |
@classmethod
|
|
@@ -367,6 +487,8 @@ class GazeLLE:
|
|
| 367 |
dispatch: str = "auto",
|
| 368 |
max_heads: int = DEFAULT_MAX_HEADS,
|
| 369 |
warmup: bool = True,
|
|
|
|
|
|
|
| 370 |
) -> "GazeLLE":
|
| 371 |
"""Load the weights, open the device, build the model and capture the traces.
|
| 372 |
|
|
@@ -381,11 +503,22 @@ class GazeLLE:
|
|
| 381 |
dispatch: ``"auto"`` | ``"eth"`` | ``"default"``, see :func:`open_device`.
|
| 382 |
max_heads: most head boxes per image (1..). Traces are captured at boot for the head-count buckets
|
| 383 |
1, 2, 3, 4, 6, 8, 10 that are <= max_heads; N heads run in the smallest bucket >= N.
|
| 384 |
-
warmup:
|
| 385 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
"""
|
| 387 |
if max_heads < 1:
|
| 388 |
raise ValueError("max_heads must be >= 1")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
weights_dir = weights_dir or os.environ.get("GAZE_LLE_WEIGHTS_DIR") or os.environ.get("TT_GAZE_LLE_WEIGHTS")
|
| 390 |
dinov2_path, gaze_path = _resolve_weights(repo_id, revision, str(weights_dir) if weights_dir else None)
|
| 391 |
|
|
@@ -412,8 +545,10 @@ class GazeLLE:
|
|
| 412 |
del ref
|
| 413 |
gc.collect()
|
| 414 |
model = cls(tt, device, owns_device=owns, max_heads=max_heads, dispatch=mode)
|
| 415 |
-
|
| 416 |
-
|
|
|
|
|
|
|
| 417 |
except BaseException:
|
| 418 |
if owns:
|
| 419 |
import ttnn
|
|
@@ -422,22 +557,121 @@ class GazeLLE:
|
|
| 422 |
raise
|
| 423 |
return model
|
| 424 |
|
| 425 |
-
def
|
| 426 |
-
"""
|
| 427 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
self._check_open()
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
|
| 442 |
# ------------------------------------------------------------------ inference
|
| 443 |
def __call__(self, image: Union[ImageLike, Sequence[ImageLike]], bboxes, *, bbox_format: str = "normalized"):
|
|
@@ -521,8 +755,11 @@ class GazeLLE:
|
|
| 521 |
def info(self) -> Dict[str, Any]:
|
| 522 |
"""Device, dispatch, grid and the captured trace buckets."""
|
| 523 |
d: Dict[str, Any] = {"max_heads": self.max_heads, "dispatch": self.dispatch, "closed": self._closed,
|
| 524 |
-
"input": "uint8 448x448x3" if self._uint8_input else "float32 (1,3,448,448)"
|
| 525 |
-
|
|
|
|
|
|
|
|
|
|
| 526 |
g = self.device.compute_with_storage_grid_size()
|
| 527 |
d["grid"] = (g.x, g.y)
|
| 528 |
if getattr(self._tt, "fused", False):
|
|
|
|
| 3 |
|
| 4 |
from gaze_lle import GazeLLE
|
| 5 |
|
| 6 |
+
with GazeLLE.from_pretrained() as model: # opens device 0, loads weights, captures traces, warms up
|
| 7 |
+
result = model("media/source_1.png", [[116, 28, 176, 104]], bbox_format="pixels") # path from the repo root
|
| 8 |
print(result.gaze_xy, result.inout) # (N, 2) pixels, (N,) P(target in frame)
|
| 9 |
|
| 10 |
``model(image, bboxes)`` does the same host work as the HTTP server's ``POST /predict`` (RGB, squash to 448x448 with
|
|
|
|
| 18 |
import math
|
| 19 |
import os
|
| 20 |
import re
|
| 21 |
+
import sys
|
| 22 |
+
import tempfile
|
| 23 |
import threading
|
| 24 |
+
import time
|
| 25 |
import warnings
|
| 26 |
from concurrent.futures import ThreadPoolExecutor
|
| 27 |
from dataclasses import dataclass
|
|
|
|
| 34 |
|
| 35 |
from gaze_lle._paths import tt_metal_home
|
| 36 |
|
| 37 |
+
__all__ = ["GazeLLE", "GazeResult", "open_device", "visualize", "parse_warmup_variants", "WARMUP_INPUTS",
|
| 38 |
+
"DEFAULT_WARMUP_VARIANTS"]
|
| 39 |
|
| 40 |
log = logging.getLogger("gaze_lle")
|
| 41 |
|
|
|
|
| 54 |
IMAGENET_STD = (0.229, 0.224, 0.225)
|
| 55 |
WARMUP_BBOX = (0.3, 0.2, 0.6, 0.5)
|
| 56 |
DEFAULT_MAX_HEADS = 10
|
| 57 |
+
# Host input paths a first call can take (see GazeLLE.warmup): 448x448 uint8 array (no resize), PIL image (resize),
|
| 58 |
+
# PNG / JPEG file (decoder plug-ins + resize), float array (rounding to uint8 + resize), predict_batch (host threads).
|
| 59 |
+
WARMUP_INPUTS = ("array", "image", "file", "float", "batch")
|
| 60 |
+
DEFAULT_WARMUP_VARIANTS = {"heads": "buckets", "inputs": "all"}
|
| 61 |
_GRID_ENV = "TT_METAL_CORE_GRID_OVERRIDE_TODEPRECATE"
|
| 62 |
|
| 63 |
ImageLike = Union[str, os.PathLike, Image.Image, np.ndarray, torch.Tensor]
|
|
|
|
| 270 |
return fetch(DINOV2_FILE), fetch(GAZE_FILE)
|
| 271 |
|
| 272 |
|
| 273 |
+
# --------------------------------------------------------------------------------------
|
| 274 |
+
# Console noise
|
| 275 |
+
# --------------------------------------------------------------------------------------
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _console_setup(verbose: bool) -> None:
|
| 279 |
+
"""verbose=False: tt-metal / UMD C++ logs at ``error`` and ttnn's loguru at ``WARNING`` (both only when the
|
| 280 |
+
variable is not set yet, and only before ttnn is first imported: they are read at import). Errors stay visible.
|
| 281 |
+
verbose=True: tt-metal keeps its own default (info) and the ``gaze_lle`` logger prints INFO to stderr."""
|
| 282 |
+
if verbose:
|
| 283 |
+
if not log.handlers and not logging.getLogger().handlers:
|
| 284 |
+
h = logging.StreamHandler()
|
| 285 |
+
h.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
|
| 286 |
+
log.addHandler(h)
|
| 287 |
+
if log.level == logging.NOTSET or log.level > logging.INFO:
|
| 288 |
+
log.setLevel(logging.INFO)
|
| 289 |
+
return
|
| 290 |
+
if "ttnn" not in sys.modules:
|
| 291 |
+
os.environ.setdefault("TT_LOGGER_LEVEL", "error")
|
| 292 |
+
os.environ.setdefault("LOGURU_LEVEL", "WARNING")
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
# --------------------------------------------------------------------------------------
|
| 296 |
+
# Warm-up variants
|
| 297 |
+
# --------------------------------------------------------------------------------------
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _as_list(v, what: str) -> list:
|
| 301 |
+
if isinstance(v, (str, int)) and not isinstance(v, bool):
|
| 302 |
+
return [v]
|
| 303 |
+
try:
|
| 304 |
+
return list(v)
|
| 305 |
+
except TypeError:
|
| 306 |
+
raise ValueError(f"warm-up {what} must be a value or a list of values, got {v!r}") from None
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def parse_warmup_variants(spec: Any, max_heads: int, buckets: Sequence[int]) -> Tuple[List[int], List[str]]:
|
| 310 |
+
"""``warmup_variants`` spec -> (head counts, host input kinds) to prepare.
|
| 311 |
+
|
| 312 |
+
``spec``: ``None`` / ``False`` / ``"none"`` (nothing), ``True`` / ``"default"`` (``DEFAULT_WARMUP_VARIANTS``),
|
| 313 |
+
``"all"`` (every head count 1..max_heads and every input kind), or a dict with the keys ``heads`` and / or
|
| 314 |
+
``inputs`` (a missing key takes its default):
|
| 315 |
+
|
| 316 |
+
* ``heads``: ``"buckets"`` (the captured head-count buckets <= max_heads, which cover every N up to the largest
|
| 317 |
+
bucket), ``"all"`` (1..max_heads), an int, or a list of ints; ``None`` / ``[]`` = none.
|
| 318 |
+
* ``inputs``: ``"all"``, one of ``WARMUP_INPUTS``, or a list of them; ``None`` / ``[]`` = none.
|
| 319 |
+
"""
|
| 320 |
+
if spec is None or spec is False or spec == "none":
|
| 321 |
+
return [], []
|
| 322 |
+
if spec is True or spec == "default":
|
| 323 |
+
spec = DEFAULT_WARMUP_VARIANTS
|
| 324 |
+
elif spec == "all":
|
| 325 |
+
spec = {"heads": "all", "inputs": "all"}
|
| 326 |
+
if not isinstance(spec, dict):
|
| 327 |
+
raise ValueError(f"warmup_variants must be None, 'default', 'all' or a dict, got {spec!r}")
|
| 328 |
+
bad = set(spec) - {"heads", "inputs"}
|
| 329 |
+
if bad:
|
| 330 |
+
raise ValueError(f"warmup_variants: unknown keys {sorted(bad)}; use 'heads' and 'inputs'")
|
| 331 |
+
full = dict(DEFAULT_WARMUP_VARIANTS, **spec)
|
| 332 |
+
hv, iv = full["heads"], full["inputs"]
|
| 333 |
+
if hv is None:
|
| 334 |
+
heads: List[int] = []
|
| 335 |
+
elif hv == "buckets":
|
| 336 |
+
heads = sorted({int(b) for b in buckets if int(b) <= max_heads}) or [1]
|
| 337 |
+
elif hv == "all":
|
| 338 |
+
heads = list(range(1, max_heads + 1))
|
| 339 |
+
else:
|
| 340 |
+
heads = []
|
| 341 |
+
for h in _as_list(hv, "heads"):
|
| 342 |
+
if isinstance(h, bool) or not isinstance(h, _NUM) or int(h) != h or not 1 <= int(h) <= max_heads:
|
| 343 |
+
raise ValueError(f"warm-up head count {h!r} must be an integer in 1..max_heads ({max_heads})")
|
| 344 |
+
heads.append(int(h))
|
| 345 |
+
heads = sorted(set(heads))
|
| 346 |
+
if iv is None:
|
| 347 |
+
inputs: List[str] = []
|
| 348 |
+
elif iv == "all":
|
| 349 |
+
inputs = list(WARMUP_INPUTS)
|
| 350 |
+
else:
|
| 351 |
+
inputs = []
|
| 352 |
+
for k in _as_list(iv, "inputs"):
|
| 353 |
+
if k not in WARMUP_INPUTS:
|
| 354 |
+
raise ValueError(f"warm-up input kind {k!r} must be one of {WARMUP_INPUTS}")
|
| 355 |
+
if k not in inputs:
|
| 356 |
+
inputs.append(k)
|
| 357 |
+
return heads, inputs
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def _dummy_image(width: int, height: int, seed: int) -> np.ndarray:
|
| 361 |
+
"""A picture-like (H, W, 3) uint8 dummy: smooth colour gradients plus noise (PNG / JPEG coders do real work on
|
| 362 |
+
it, unlike on a flat image). Only used for warm-up; its outputs are discarded."""
|
| 363 |
+
rng = np.random.default_rng(seed)
|
| 364 |
+
yy, xx = np.mgrid[0:height, 0:width].astype(np.float32)
|
| 365 |
+
base = np.stack([xx / max(1, width - 1), yy / max(1, height - 1), (xx + yy) / max(1, width + height - 2)], -1)
|
| 366 |
+
img = base * 200.0 + rng.normal(0.0, 20.0, size=(height, width, 3)).astype(np.float32)
|
| 367 |
+
return np.clip(img, 0, 255).astype(np.uint8)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def _dummy_boxes(n: int, seed: int) -> List[List[float]]:
|
| 371 |
+
"""n distinct normalised head boxes on a grid (each covers several cells of the 32x32 feature grid)."""
|
| 372 |
+
rng = np.random.default_rng(seed)
|
| 373 |
+
out = []
|
| 374 |
+
for i in range(n):
|
| 375 |
+
x = 0.05 + 0.18 * (i % 5) + rng.uniform(0, 0.02)
|
| 376 |
+
y = 0.08 + 0.4 * (i // 5 % 2) + rng.uniform(0, 0.02)
|
| 377 |
+
out.append([x, y, x + 0.12, y + 0.16])
|
| 378 |
+
return out
|
| 379 |
+
|
| 380 |
+
|
| 381 |
# --------------------------------------------------------------------------------------
|
| 382 |
# Device
|
| 383 |
# --------------------------------------------------------------------------------------
|
|
|
|
| 469 |
fused = bool(getattr(tt_model, "fused", False))
|
| 470 |
cfg = getattr(tt_model, "fused_cfg", None)
|
| 471 |
self._uint8_input = fused and cfg is not None and getattr(cfg, "input", "") == "raw"
|
| 472 |
+
self._warm_lock = threading.Lock()
|
| 473 |
+
self._warm_done: set = set() # ("device", trace bucket) / ("input", kind) already warmed
|
| 474 |
+
self._traces_ready = False
|
| 475 |
+
self.warmup_report: Dict[str, Any] = {"traces_s": 0.0, "heads": {}, "inputs": {}}
|
| 476 |
|
| 477 |
# ------------------------------------------------------------------ construction
|
| 478 |
@classmethod
|
|
|
|
| 487 |
dispatch: str = "auto",
|
| 488 |
max_heads: int = DEFAULT_MAX_HEADS,
|
| 489 |
warmup: bool = True,
|
| 490 |
+
warmup_variants: Any = "default",
|
| 491 |
+
verbose: bool = False,
|
| 492 |
) -> "GazeLLE":
|
| 493 |
"""Load the weights, open the device, build the model and capture the traces.
|
| 494 |
|
|
|
|
| 503 |
dispatch: ``"auto"`` | ``"eth"`` | ``"default"``, see :func:`open_device`.
|
| 504 |
max_heads: most head boxes per image (1..). Traces are captured at boot for the head-count buckets
|
| 505 |
1, 2, 3, 4, 6, 8, 10 that are <= max_heads; N heads run in the smallest bucket >= N.
|
| 506 |
+
warmup: False skips all warm-up (same as ``warmup_variants=None``): the first calls then capture
|
| 507 |
+
traces and compile (seconds).
|
| 508 |
+
warmup_variants: what to prepare now so that the FIRST real call of each variant is as fast as the
|
| 509 |
+
later ones; see :meth:`warmup` and :func:`parse_warmup_variants`. Default
|
| 510 |
+
``{"heads": "buckets", "inputs": "all"}``: every head count 1..min(max_heads, 10) and every host input
|
| 511 |
+
path. ``"all"`` also prepares every head count above 10 (one more trace each); ``None`` = nothing.
|
| 512 |
+
verbose: False (default) keeps the console quiet: tt-metal / UMD logs at ``error`` level and ttnn's
|
| 513 |
+
loguru at ``WARNING`` (set before ttnn is imported; your own ``TT_LOGGER_LEVEL`` / ``LOGURU_LEVEL``
|
| 514 |
+
win). True: tt-metal's normal info logs and ``gaze_lle`` INFO messages (load and warm-up times).
|
| 515 |
"""
|
| 516 |
if max_heads < 1:
|
| 517 |
raise ValueError("max_heads must be >= 1")
|
| 518 |
+
if not warmup:
|
| 519 |
+
warmup_variants = None
|
| 520 |
+
_console_setup(verbose)
|
| 521 |
+
t_start = time.perf_counter()
|
| 522 |
weights_dir = weights_dir or os.environ.get("GAZE_LLE_WEIGHTS_DIR") or os.environ.get("TT_GAZE_LLE_WEIGHTS")
|
| 523 |
dinov2_path, gaze_path = _resolve_weights(repo_id, revision, str(weights_dir) if weights_dir else None)
|
| 524 |
|
|
|
|
| 545 |
del ref
|
| 546 |
gc.collect()
|
| 547 |
model = cls(tt, device, owns_device=owns, max_heads=max_heads, dispatch=mode)
|
| 548 |
+
model.warmup_report["build_s"] = round(time.perf_counter() - t_start, 3)
|
| 549 |
+
heads, inputs = parse_warmup_variants(warmup_variants, max_heads, model._cfg_buckets())
|
| 550 |
+
if heads or inputs:
|
| 551 |
+
model.warmup(heads=heads, inputs=inputs)
|
| 552 |
except BaseException:
|
| 553 |
if owns:
|
| 554 |
import ttnn
|
|
|
|
| 557 |
raise
|
| 558 |
return model
|
| 559 |
|
| 560 |
+
def _cfg_buckets(self) -> List[int]:
|
| 561 |
+
"""Head-count buckets the traces are captured for (``TT_FUSED_TRACE_HEADS`` <= max_heads)."""
|
| 562 |
+
cfg = getattr(self._tt, "fused_cfg", None)
|
| 563 |
+
heads = getattr(cfg, "trace_heads", None) or (1,)
|
| 564 |
+
return sorted({int(b) for b in heads if int(b) <= self.max_heads}) or [1]
|
| 565 |
+
|
| 566 |
+
def _traced(self) -> bool:
|
| 567 |
+
cfg = getattr(self._tt, "fused_cfg", None)
|
| 568 |
+
return bool(getattr(self._tt, "fused", False)) and bool(getattr(cfg, "trace", True))
|
| 569 |
+
|
| 570 |
+
def _bucket_of(self, n: int) -> int:
|
| 571 |
+
"""The trace bucket N heads run in (as TtGazeLLE._run_traced picks it); N itself when no bucket fits."""
|
| 572 |
+
if not self._traced():
|
| 573 |
+
return n
|
| 574 |
+
caught = getattr(self._tt, "trace_buckets", None)
|
| 575 |
+
caught = list(caught) if caught is not None else self._cfg_buckets()
|
| 576 |
+
fits = [b for b in caught if b >= n]
|
| 577 |
+
return min(fits) if fits else n
|
| 578 |
+
|
| 579 |
+
def warmup(self, heads: Any = "buckets", inputs: Any = "all", iters: int = 2) -> Dict[str, Any]:
|
| 580 |
+
"""Prepare variants now so that their FIRST real call is as fast as the later ones. Idempotent: variants
|
| 581 |
+
that are already warm are skipped (a second call costs microseconds).
|
| 582 |
+
|
| 583 |
+
Args:
|
| 584 |
+
heads: head counts to prepare. ``"buckets"`` (default) = the captured head-count buckets <= max_heads
|
| 585 |
+
(1, 2, 3, 4, 6, 8, 10 by default); together they cover every N from 1 to the largest bucket, because
|
| 586 |
+
N heads run in the smallest bucket >= N. ``"all"`` = 1..max_heads; an int or a list of ints.
|
| 587 |
+
For each head count: the trace of its bucket is captured if needed (one eager compile run + capture,
|
| 588 |
+
about 1 s for a new bucket), then ``iters`` real forwards run through the public call path (host
|
| 589 |
+
pre-processing, trace replay, readback, output decoding) on a dummy picture with N dummy boxes.
|
| 590 |
+
inputs: host input paths to prepare: ``"all"`` (default) or some of ``"array"`` (448x448 uint8 array,
|
| 591 |
+
no resize), ``"image"`` (PIL image, resize), ``"file"`` (PNG and JPEG files: decoder plug-ins),
|
| 592 |
+
``"float"`` (float array), ``"batch"`` (``predict_batch`` host threads). One call each, 1 head.
|
| 593 |
+
iters: forwards per new head-count bucket (default 2, like the HTTP server).
|
| 594 |
+
|
| 595 |
+
Returns (and keeps in ``model.warmup_report``) the seconds spent per variant. Warm-up runs real forwards on
|
| 596 |
+
dummy data and drops their outputs; nothing is cached, so later results do not change.
|
| 597 |
+
"""
|
| 598 |
self._check_open()
|
| 599 |
+
head_list, input_list = parse_warmup_variants({"heads": heads, "inputs": inputs}, self.max_heads,
|
| 600 |
+
self._cfg_buckets())
|
| 601 |
+
rep = self.warmup_report
|
| 602 |
+
with self._warm_lock:
|
| 603 |
+
tt = self._tt
|
| 604 |
+
# head counts above the largest bucket get a trace of their own size (what their first real call
|
| 605 |
+
# would capture); all new traces are captured together, before the forwards below
|
| 606 |
+
extra = [n for n in head_list if self._traced() and self._bucket_of(n) == n
|
| 607 |
+
and n not in (getattr(tt, "trace_buckets", None) or self._cfg_buckets())]
|
| 608 |
+
did = False
|
| 609 |
+
if not self._traces_ready or extra:
|
| 610 |
+
did = True
|
| 611 |
+
t = time.perf_counter()
|
| 612 |
+
new = ([] if self._traces_ready else self._cfg_buckets()) + extra
|
| 613 |
+
if getattr(tt, "fused", False):
|
| 614 |
+
with self._lock, torch.inference_mode():
|
| 615 |
+
tt.warmup(heads=new) # capture the bucket traces (what the server does at boot)
|
| 616 |
+
self._sync()
|
| 617 |
+
self._traces_ready = True
|
| 618 |
+
rep["traces_s"] = round(rep["traces_s"] + time.perf_counter() - t, 3)
|
| 619 |
+
log.info("gaze_lle: traces for head buckets %s ready (%.2f s)", new, time.perf_counter() - t)
|
| 620 |
+
img448 = _dummy_image(INPUT_SIZE, INPUT_SIZE, seed=1)
|
| 621 |
+
for n in head_list:
|
| 622 |
+
bucket = self._bucket_of(n)
|
| 623 |
+
if ("device", bucket) in self._warm_done:
|
| 624 |
+
continue
|
| 625 |
+
t = time.perf_counter()
|
| 626 |
+
boxes = _dummy_boxes(n, seed=n)
|
| 627 |
+
for i in range(max(1, int(iters))):
|
| 628 |
+
r = self(img448 if i % 2 == 0 else img448[::-1].copy(), boxes)
|
| 629 |
+
_ = r.gaze_xy, r.score
|
| 630 |
+
self._sync()
|
| 631 |
+
self._warm_done.add(("device", bucket))
|
| 632 |
+
rep["heads"][bucket] = round(time.perf_counter() - t, 3)
|
| 633 |
+
log.info("gaze_lle: head bucket %d warm (%.3f s)", bucket, rep["heads"][bucket])
|
| 634 |
+
did = True
|
| 635 |
+
for kind in input_list:
|
| 636 |
+
if ("input", kind) in self._warm_done:
|
| 637 |
+
continue
|
| 638 |
+
t = time.perf_counter()
|
| 639 |
+
self._warm_input(kind)
|
| 640 |
+
self._warm_done.add(("input", kind))
|
| 641 |
+
rep["inputs"][kind] = round(time.perf_counter() - t, 3)
|
| 642 |
+
log.info("gaze_lle: input path %r warm (%.3f s)", kind, rep["inputs"][kind])
|
| 643 |
+
did = True
|
| 644 |
+
if did:
|
| 645 |
+
# Start the caller's calls with empty GC generations (the build and warm-up made many objects; a
|
| 646 |
+
# collection would otherwise fall on one of the first real calls), then one more forward so that the
|
| 647 |
+
# host caches are warm again after the collection (measured: without it, call 1 is ~0.35 ms slower).
|
| 648 |
+
gc.collect()
|
| 649 |
+
_ = self(img448, _dummy_boxes(1, seed=0)).gaze_xy
|
| 650 |
+
return rep
|
| 651 |
+
|
| 652 |
+
def _warm_input(self, kind: str) -> None:
|
| 653 |
+
"""One real call through a host input path, on dummy data of a typical camera / dataset size."""
|
| 654 |
+
box = [_dummy_boxes(1, seed=0)[0]]
|
| 655 |
+
pic = _dummy_image(640, 480, seed=2)
|
| 656 |
+
if kind == "array":
|
| 657 |
+
r = [self(_dummy_image(INPUT_SIZE, INPUT_SIZE, seed=3), box)]
|
| 658 |
+
elif kind == "image":
|
| 659 |
+
r = [self(Image.fromarray(pic), box), self(Image.fromarray(pic).convert("RGBA"), box)]
|
| 660 |
+
elif kind == "float":
|
| 661 |
+
r = [self(pic.astype(np.float32) / 255.0, box), self(torch.from_numpy(pic).permute(2, 0, 1), box)]
|
| 662 |
+
elif kind == "file":
|
| 663 |
+
with tempfile.TemporaryDirectory(prefix="gaze_lle_warmup_") as d:
|
| 664 |
+
r = []
|
| 665 |
+
for ext, kw in (("png", {}), ("jpg", {"quality": 90})):
|
| 666 |
+
f = os.path.join(d, f"warmup.{ext}")
|
| 667 |
+
Image.fromarray(pic).save(f, **kw)
|
| 668 |
+
r.append(self(f, box))
|
| 669 |
+
elif kind == "batch":
|
| 670 |
+
r = self.predict_batch([Image.fromarray(pic), pic], [box, box])
|
| 671 |
+
else: # parse_warmup_variants validates the names
|
| 672 |
+
raise ValueError(kind)
|
| 673 |
+
for x in r:
|
| 674 |
+
_ = x.gaze_xy, x.score, x.to_dict()
|
| 675 |
|
| 676 |
# ------------------------------------------------------------------ inference
|
| 677 |
def __call__(self, image: Union[ImageLike, Sequence[ImageLike]], bboxes, *, bbox_format: str = "normalized"):
|
|
|
|
| 755 |
def info(self) -> Dict[str, Any]:
|
| 756 |
"""Device, dispatch, grid and the captured trace buckets."""
|
| 757 |
d: Dict[str, Any] = {"max_heads": self.max_heads, "dispatch": self.dispatch, "closed": self._closed,
|
| 758 |
+
"input": "uint8 448x448x3" if self._uint8_input else "float32 (1,3,448,448)",
|
| 759 |
+
"warm_heads_buckets": sorted(b for k, b in self._warm_done if k == "device"),
|
| 760 |
+
"warm_inputs": [k for k in WARMUP_INPUTS if ("input", k) in self._warm_done],
|
| 761 |
+
"warmup_report": self.warmup_report}
|
| 762 |
+
if not self._closed and self.device is not None:
|
| 763 |
g = self.device.compute_with_storage_grid_size()
|
| 764 |
d["grid"] = (g.x, g.y)
|
| 765 |
if getattr(self._tt, "fused", False):
|
code/gaze_lle/tests/test_api_host.py
CHANGED
|
@@ -55,6 +55,11 @@ class StubTT:
|
|
| 55 |
|
| 56 |
def warmup(self, heads=None):
|
| 57 |
self.warm = list(heads)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
def release_traces(self):
|
| 60 |
self.released = True
|
|
@@ -245,3 +250,106 @@ def test_eth_dispatch_detection_is_safe(monkeypatch, tmp_path):
|
|
| 245 |
ld.write_text("&& !(defined(ARCH_BLACKHOLE) && (defined(COMPILE_FOR_IERISC) || "
|
| 246 |
"defined(COMPILE_FOR_SUBORDINATE_IERISC)))\n")
|
| 247 |
assert api.eth_dispatch_available() is True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
def warmup(self, heads=None):
|
| 57 |
self.warm = list(heads)
|
| 58 |
+
self.captured = sorted(set(getattr(self, "captured", [])) | set(self.warm))
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def trace_buckets(self):
|
| 62 |
+
return getattr(self, "captured", [])
|
| 63 |
|
| 64 |
def release_traces(self):
|
| 65 |
self.released = True
|
|
|
|
| 250 |
ld.write_text("&& !(defined(ARCH_BLACKHOLE) && (defined(COMPILE_FOR_IERISC) || "
|
| 251 |
"defined(COMPILE_FOR_SUBORDINATE_IERISC)))\n")
|
| 252 |
assert api.eth_dispatch_available() is True
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
# ------------------------------------------------------------------ warm-up API
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def test_warmup_variants_spec():
|
| 259 |
+
p = api.parse_warmup_variants
|
| 260 |
+
b = [1, 2, 3, 4, 6, 8, 10]
|
| 261 |
+
assert p("default", 10, b) == (b, list(api.WARMUP_INPUTS)) == p(True, 10, b) == p({}, 10, b)
|
| 262 |
+
assert p(None, 10, b) == ([], []) == p(False, 10, b) == p("none", 10, b)
|
| 263 |
+
assert p("all", 12, b) == (list(range(1, 13)), list(api.WARMUP_INPUTS))
|
| 264 |
+
assert p({"heads": "buckets"}, 4, b) == ([1, 2, 3, 4], list(api.WARMUP_INPUTS))
|
| 265 |
+
assert p({"heads": [3, 1, 3], "inputs": "file"}, 10, b) == ([1, 3], ["file"])
|
| 266 |
+
assert p({"heads": 5, "inputs": None}, 10, b) == ([5], [])
|
| 267 |
+
for bad in ({"heads": 0}, {"heads": 11}, {"heads": [1.5]}, {"heads": True}, {"inputs": "webp"},
|
| 268 |
+
{"head": 1}, "everything", 3):
|
| 269 |
+
with pytest.raises(ValueError):
|
| 270 |
+
p(bad, 10, b)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def test_from_pretrained_signature():
|
| 274 |
+
import inspect
|
| 275 |
+
|
| 276 |
+
sig = inspect.signature(api.GazeLLE.from_pretrained)
|
| 277 |
+
assert sig.parameters["warmup_variants"].default == "default"
|
| 278 |
+
assert sig.parameters["verbose"].default is False
|
| 279 |
+
assert sig.parameters["warmup"].default is True
|
| 280 |
+
w = inspect.signature(api.GazeLLE.warmup)
|
| 281 |
+
assert [k for k in w.parameters][1:] == ["heads", "inputs", "iters"]
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def test_warmup_covers_buckets_and_inputs_and_is_idempotent():
|
| 285 |
+
stub = StubTT()
|
| 286 |
+
m = api.GazeLLE(stub, None, owns_device=False, max_heads=10)
|
| 287 |
+
rep = m.warmup()
|
| 288 |
+
assert stub.warm == [1, 2, 3, 4, 6, 8, 10]
|
| 289 |
+
assert sorted(rep["heads"]) == [1, 2, 3, 4, 6, 8, 10] and list(rep["inputs"]) == list(api.WARMUP_INPUTS)
|
| 290 |
+
# every bucket ran real forwards with that many dummy boxes (2 iterations each)
|
| 291 |
+
counts = [len(bb) for _, bb in stub.calls]
|
| 292 |
+
for n in (1, 2, 3, 4, 6, 8, 10):
|
| 293 |
+
assert counts.count(n) >= 2, (n, counts)
|
| 294 |
+
# the dummy inputs are pictures of the right size, not zeros
|
| 295 |
+
assert all(tuple(im.shape) == (1, 448, 448, 3) and im.dtype == torch.uint8 and int(im.max()) > 0
|
| 296 |
+
for im, _ in stub.calls)
|
| 297 |
+
info = m.info()
|
| 298 |
+
assert info["warm_heads_buckets"] == [1, 2, 3, 4, 6, 8, 10] and info["warm_inputs"] == list(api.WARMUP_INPUTS)
|
| 299 |
+
n_calls = len(stub.calls)
|
| 300 |
+
m.warmup() # idempotent
|
| 301 |
+
m.warmup(heads=[5, 7, 9]) # N = 5, 7, 9 run in buckets 6, 8, 10: already warm
|
| 302 |
+
m.warmup(heads="all", inputs="file")
|
| 303 |
+
assert len(stub.calls) == n_calls
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def test_warmup_above_largest_bucket():
|
| 307 |
+
stub = StubTT()
|
| 308 |
+
m = api.GazeLLE(stub, None, owns_device=False, max_heads=12)
|
| 309 |
+
m.warmup(heads="buckets", inputs=None)
|
| 310 |
+
assert stub.warm == [1, 2, 3, 4, 6, 8, 10]
|
| 311 |
+
n0 = len(stub.calls)
|
| 312 |
+
m.warmup(heads=[11], inputs=[], iters=1) # its own bucket (as the first real call with 11 heads would)
|
| 313 |
+
assert [len(bb) for _, bb in stub.calls[n0:]] == [11, 1] # + the cache re-warm forward after gc.collect
|
| 314 |
+
with pytest.raises(ValueError):
|
| 315 |
+
m.warmup(heads=[13])
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def test_warmup_does_not_change_results():
|
| 319 |
+
m_cold, m_warm = _model(), _model()
|
| 320 |
+
m_warm.warmup(heads="all", inputs="all")
|
| 321 |
+
for x, bb, fmt in ((DEMO, DEMO_BOXES_PX, "pixels"), (np.array(Image.open(DEMO).convert("RGB")), [[0.1, 0.1, 0.3, 0.4]],
|
| 322 |
+
"normalized")):
|
| 323 |
+
a, b = m_cold(x, bb, bbox_format=fmt), m_warm(x, bb, bbox_format=fmt)
|
| 324 |
+
assert torch.equal(a.heatmap, b.heatmap) and torch.equal(a.inout, b.inout)
|
| 325 |
+
assert torch.equal(m_cold._tt.calls[-1][0], m_warm._tt.calls[-1][0])
|
| 326 |
+
# results are new objects every call (nothing cached)
|
| 327 |
+
r1, r2 = m_warm(DEMO, DEMO_BOXES_PX, bbox_format="pixels"), m_warm(DEMO, DEMO_BOXES_PX, bbox_format="pixels")
|
| 328 |
+
assert r1 is not r2 and r1.heatmap is not r2.heatmap
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def test_warmup_closed_model_raises():
|
| 332 |
+
m = _model()
|
| 333 |
+
m.close()
|
| 334 |
+
with pytest.raises(RuntimeError):
|
| 335 |
+
m.warmup()
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
@pytest.mark.parametrize("preset", [None, "info"])
|
| 339 |
+
def test_quiet_console_env(preset):
|
| 340 |
+
"""verbose=False sets tt-metal / loguru levels before ttnn is imported, and keeps a level the user set."""
|
| 341 |
+
code = ("import os; from gaze_lle import api; api._console_setup(False); "
|
| 342 |
+
"print(os.environ.get('TT_LOGGER_LEVEL'), os.environ.get('LOGURU_LEVEL'))")
|
| 343 |
+
env = {k: v for k, v in __import__("os").environ.items() if k not in ("TT_LOGGER_LEVEL", "LOGURU_LEVEL")}
|
| 344 |
+
if preset:
|
| 345 |
+
env["TT_LOGGER_LEVEL"] = preset
|
| 346 |
+
r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env)
|
| 347 |
+
assert r.returncode == 0, r.stderr
|
| 348 |
+
assert r.stdout.split() == [preset or "error", "WARNING"]
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def test_verbose_enables_gaze_lle_info_logs():
|
| 352 |
+
code = ("import logging; from gaze_lle import api; api._console_setup(True); "
|
| 353 |
+
"api.log.info('hello-info'); print(api.log.getEffectiveLevel())")
|
| 354 |
+
r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
|
| 355 |
+
assert r.returncode == 0 and "hello-info" in r.stderr and r.stdout.strip() == "20", (r.stdout, r.stderr)
|
code/gaze_lle/tests/test_api_warmup_device.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-FileCopyrightText: (c) 2026 Tenstorrent AI ULC
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
|
| 4 |
+
"""Device test: after ``GazeLLE.from_pretrained()`` the FIRST real call of each warmed variant is fast, and warm-up
|
| 5 |
+
does not change outputs.
|
| 6 |
+
|
| 7 |
+
cd models/gaze-lle-p150
|
| 8 |
+
source <tools>/chipenv.sh <chip> .venv # one chip, device_id 0
|
| 9 |
+
.venv/bin/python -m pytest code/gaze_lle/tests/test_api_warmup_device.py -q -s
|
| 10 |
+
|
| 11 |
+
Each check runs in a FRESH child process (nothing warm from earlier tests):
|
| 12 |
+
|
| 13 |
+
1. ``test_first_call_fast``: default ``from_pretrained()``; then for N = 1, 3, 10 heads and the input paths
|
| 14 |
+
448x448 uint8 array, PNG file and JPEG file, the first call with a NEW real picture (repo ``media/``) must be within
|
| 15 |
+
``max(1.15 x median, median + 0.5 ms)`` of the median of the next calls on the same picture (checked in two fresh
|
| 16 |
+
processes; a variant fails when it is slow in both, so a one-off hiccup of a shared host does not fail the test).
|
| 17 |
+
2. ``test_warmup_does_not_change_outputs``: the same calls with ``warmup_variants=None`` (cold, traces captured on
|
| 18 |
+
first use) and with ``warmup_variants="all"`` give bit-identical heatmaps and inout.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import json
|
| 24 |
+
import os
|
| 25 |
+
import subprocess
|
| 26 |
+
import sys
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
import pytest
|
| 30 |
+
|
| 31 |
+
if os.environ.get("TT_VISIBLE_DEVICES", "").lower() == "none":
|
| 32 |
+
pytest.skip("no device (TT_VISIBLE_DEVICES=none)", allow_module_level=True)
|
| 33 |
+
pytest.importorskip("ttnn")
|
| 34 |
+
|
| 35 |
+
CODE = Path(__file__).resolve().parents[2]
|
| 36 |
+
REPO = CODE.parent
|
| 37 |
+
|
| 38 |
+
_CHILD = r"""
|
| 39 |
+
import json, statistics, sys, tempfile, time
|
| 40 |
+
from pathlib import Path
|
| 41 |
+
mode, out = sys.argv[1], Path(sys.argv[2])
|
| 42 |
+
repo = Path(sys.argv[3])
|
| 43 |
+
pics = [repo / "media" / f"source_{i}.png" for i in (1, 2, 3, 4)] + [repo / "media" / f"target_{i}.png" for i in (1, 2)]
|
| 44 |
+
boxes = {1: [[0.23, 0.08, 0.35, 0.31]],
|
| 45 |
+
3: [[0.23, 0.08, 0.35, 0.31], [0.54, 0.11, 0.60, 0.24], [0.17, 0.17, 0.25, 0.26]],
|
| 46 |
+
10: [[0.05 + 0.09 * i, 0.1 + 0.05 * (i % 3), 0.13 + 0.09 * i, 0.3 + 0.05 * (i % 3)] for i in range(10)]}
|
| 47 |
+
from gaze_lle import GazeLLE # noqa: E402 (no PIL decoding in this process before the model is built)
|
| 48 |
+
from PIL import Image # noqa: E402
|
| 49 |
+
import numpy as np # noqa: E402
|
| 50 |
+
|
| 51 |
+
def variants(tmp):
|
| 52 |
+
# (name, input, boxes); every input is a picture not used by the warm-up
|
| 53 |
+
v = []
|
| 54 |
+
for k, n in enumerate((1, 3, 10)):
|
| 55 |
+
with Image.open(pics[k]) as im:
|
| 56 |
+
v.append((f"array N={n}", np.array(im.convert("RGB").resize((448, 448), Image.BILINEAR)), boxes[n]))
|
| 57 |
+
v.append(("png N=3", str(pics[3]), boxes[3]))
|
| 58 |
+
jpg = Path(tmp) / "t.jpg"
|
| 59 |
+
import subprocess
|
| 60 |
+
subprocess.run([sys.executable, "-c", f"from PIL import Image; Image.open({str(pics[4])!r}).convert('RGB').save({str(jpg)!r}, quality=90)"], check=True)
|
| 61 |
+
v.append(("jpg N=1", str(jpg), boxes[1]))
|
| 62 |
+
return v
|
| 63 |
+
|
| 64 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 65 |
+
vs = variants(tmp)
|
| 66 |
+
if mode == "timing":
|
| 67 |
+
model = GazeLLE.from_pretrained()
|
| 68 |
+
res = {}
|
| 69 |
+
for name, x, bb in vs:
|
| 70 |
+
t = time.perf_counter(); r = model(x, bb); r.gaze_xy; first = (time.perf_counter() - t) * 1e3
|
| 71 |
+
later = []
|
| 72 |
+
for _ in range(30):
|
| 73 |
+
t = time.perf_counter(); r = model(x, bb); r.gaze_xy; later.append((time.perf_counter() - t) * 1e3)
|
| 74 |
+
res[name] = {"first_ms": first, "median_ms": statistics.median(later), "max_ms": max(later),
|
| 75 |
+
"p90_ms": sorted(later)[int(0.9 * len(later))]}
|
| 76 |
+
model.close()
|
| 77 |
+
out.write_text(json.dumps(res))
|
| 78 |
+
else:
|
| 79 |
+
import torch
|
| 80 |
+
outs = {}
|
| 81 |
+
for spec in (None, "all"):
|
| 82 |
+
model = GazeLLE.from_pretrained(warmup_variants=spec)
|
| 83 |
+
rs = [model(x, bb) for _, x, bb in vs]
|
| 84 |
+
outs[str(spec)] = [(r.heatmap.clone(), r.inout.clone()) for r in rs]
|
| 85 |
+
model.close()
|
| 86 |
+
torch.save(outs, out)
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _child(mode: str, out: Path) -> None:
|
| 91 |
+
r = subprocess.run([sys.executable, "-c", _CHILD, mode, str(out), str(REPO)], capture_output=True, text=True,
|
| 92 |
+
timeout=1800)
|
| 93 |
+
assert r.returncode == 0, r.stdout[-3000:] + r.stderr[-3000:]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_first_call_fast(tmp_path):
|
| 97 |
+
# Two fresh processes; a variant fails only when its first call is slow in BOTH (a real first-use cost shows
|
| 98 |
+
# every time; a scheduling hiccup of the shared host, which also hits later calls, rarely hits both).
|
| 99 |
+
runs = []
|
| 100 |
+
for k in range(2):
|
| 101 |
+
out = tmp_path / f"t{k}.json"
|
| 102 |
+
_child("timing", out)
|
| 103 |
+
runs.append(json.loads(out.read_text()))
|
| 104 |
+
print()
|
| 105 |
+
bad = []
|
| 106 |
+
for name in runs[0]:
|
| 107 |
+
slow = []
|
| 108 |
+
for k, res in enumerate(runs):
|
| 109 |
+
d = res[name]
|
| 110 |
+
print(f" run {k} {name:12s} first {d['first_ms']:7.3f} ms median of next 30 {d['median_ms']:7.3f} ms "
|
| 111 |
+
f"ratio {d['first_ms'] / d['median_ms']:.3f} (p90 {d['p90_ms']:.3f}, max {d['max_ms']:.3f})")
|
| 112 |
+
slow.append(d["first_ms"] > max(1.15 * d["median_ms"], d["median_ms"] + 0.5))
|
| 113 |
+
if all(slow):
|
| 114 |
+
bad.append(name)
|
| 115 |
+
assert not bad, f"first call slow in both runs for {bad}: {runs}"
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def test_warmup_does_not_change_outputs(tmp_path):
|
| 119 |
+
import torch
|
| 120 |
+
|
| 121 |
+
out = tmp_path / "o.pt"
|
| 122 |
+
_child("outputs", out)
|
| 123 |
+
o = torch.load(out)
|
| 124 |
+
for (h0, i0), (h1, i1) in zip(o["None"], o["all"]):
|
| 125 |
+
assert torch.equal(h0, h1) and torch.equal(i0, i1)
|
code/gaze_lle/tt/custom_ops.py
CHANGED
|
@@ -219,6 +219,7 @@ void kernel_main() {
|
|
| 219 |
uint32_t start_unused, num_tiles;
|
| 220 |
GAZE_RANGE(get_common_arg_val<uint32_t>(0), get_common_arg_val<uint32_t>(1), get_common_arg_val<uint32_t>(2),
|
| 221 |
start_unused, num_tiles);
|
|
|
|
| 222 |
constexpr auto cb_in = tt::CBIndex::c_0;
|
| 223 |
constexpr auto cb_out = tt::CBIndex::c_16;
|
| 224 |
init_sfpu(cb_in, cb_out);
|
|
@@ -1390,6 +1391,7 @@ GAZE_RANGE_MACRO_HERE
|
|
| 1390 |
void kernel_main() {
|
| 1391 |
uint32_t start_unused, n;
|
| 1392 |
GAZE_RANGE(get_common_arg_val<uint32_t>(0), get_common_arg_val<uint32_t>(1), get_common_arg_val<uint32_t>(2), start_unused, n);
|
|
|
|
| 1393 |
constexpr uint32_t cb_x = 0, cb_c = 1, cb_out = 16;
|
| 1394 |
compute_kernel_hw_startup(cb_x, cb_c, cb_out);
|
| 1395 |
add_init(cb_x, cb_c, false);
|
|
@@ -1839,6 +1841,7 @@ void kernel_main() {
|
|
| 1839 |
uint32_t start_unused, num_tiles;
|
| 1840 |
GAZE_RANGE(get_common_arg_val<uint32_t>(0), get_common_arg_val<uint32_t>(1), get_common_arg_val<uint32_t>(2),
|
| 1841 |
start_unused, num_tiles);
|
|
|
|
| 1842 |
constexpr auto cb_in = tt::CBIndex::c_0;
|
| 1843 |
constexpr auto cb_out = tt::CBIndex::c_16;
|
| 1844 |
init_sfpu(cb_in, cb_out);
|
|
|
|
| 219 |
uint32_t start_unused, num_tiles;
|
| 220 |
GAZE_RANGE(get_common_arg_val<uint32_t>(0), get_common_arg_val<uint32_t>(1), get_common_arg_val<uint32_t>(2),
|
| 221 |
start_unused, num_tiles);
|
| 222 |
+
(void)start_unused; // compute kernels use only the count (no -Wunused warning on the JIT console)
|
| 223 |
constexpr auto cb_in = tt::CBIndex::c_0;
|
| 224 |
constexpr auto cb_out = tt::CBIndex::c_16;
|
| 225 |
init_sfpu(cb_in, cb_out);
|
|
|
|
| 1391 |
void kernel_main() {
|
| 1392 |
uint32_t start_unused, n;
|
| 1393 |
GAZE_RANGE(get_common_arg_val<uint32_t>(0), get_common_arg_val<uint32_t>(1), get_common_arg_val<uint32_t>(2), start_unused, n);
|
| 1394 |
+
(void)start_unused; // only the count is used (no -Wunused warning on the JIT console)
|
| 1395 |
constexpr uint32_t cb_x = 0, cb_c = 1, cb_out = 16;
|
| 1396 |
compute_kernel_hw_startup(cb_x, cb_c, cb_out);
|
| 1397 |
add_init(cb_x, cb_c, false);
|
|
|
|
| 1841 |
uint32_t start_unused, num_tiles;
|
| 1842 |
GAZE_RANGE(get_common_arg_val<uint32_t>(0), get_common_arg_val<uint32_t>(1), get_common_arg_val<uint32_t>(2),
|
| 1843 |
start_unused, num_tiles);
|
| 1844 |
+
(void)start_unused; // compute kernels use only the count (no -Wunused warning on the JIT console)
|
| 1845 |
constexpr auto cb_in = tt::CBIndex::c_0;
|
| 1846 |
constexpr auto cb_out = tt::CBIndex::c_16;
|
| 1847 |
init_sfpu(cb_in, cb_out);
|
code/scripts/first_call_bench.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
"""First-call latency of the Python API in a FRESH process (one variant per process).
|
| 3 |
+
|
| 4 |
+
source <tools>/chipenv.sh <chip> .venv
|
| 5 |
+
timeout -s INT 600 .venv/bin/python code/scripts/first_call_bench.py --heads 3 --input png --out /tmp/x.pt
|
| 6 |
+
|
| 7 |
+
Times ``GazeLLE.from_pretrained()``, then calls 1..10 of ONE variant (head count N, input kind), each with a NEW
|
| 8 |
+
real image (repo media/ pictures and their mirror images; none of them is the warm-up input) and new boxes, then
|
| 9 |
+
``--steady`` more calls for the steady median. Prints one JSON line; ``--out`` saves the call 1..10 outputs (for the
|
| 10 |
+
bit-identical check before/after a change).
|
| 11 |
+
|
| 12 |
+
Input kinds: u8 = (448, 448, 3) uint8 array (device fast path); pil = PIL image at the original size (host resize);
|
| 13 |
+
png / jpg = file path (decode + resize); f32 = float (H, W, 3) array in [0, 1]; batch = predict_batch of 4 images.
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import statistics
|
| 21 |
+
import sys
|
| 22 |
+
import tempfile
|
| 23 |
+
import time
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
T0 = time.perf_counter()
|
| 27 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _write_files(kind: str, tmp: Path) -> list:
|
| 31 |
+
"""png / jpg inputs: written by a CHILD process, so this process has not used PIL's decoders before the API."""
|
| 32 |
+
import subprocess
|
| 33 |
+
|
| 34 |
+
code = (f"import sys; sys.path.insert(0, {str(Path(__file__).parent)!r}); from first_call_bench import _images; "
|
| 35 |
+
f"_images({kind!r}, __import__('pathlib').Path({str(tmp)!r}), write=True)")
|
| 36 |
+
subprocess.run([sys.executable, "-c", code], check=True)
|
| 37 |
+
return [str(p) for p in sorted(tmp.glob(f"im*.{kind}"), key=lambda p: int(p.stem[2:]))]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _images(kind: str, tmp: Path, write: bool = False):
|
| 41 |
+
if kind in ("png", "jpg") and not write:
|
| 42 |
+
return _write_files(kind, tmp)
|
| 43 |
+
import numpy as np
|
| 44 |
+
from PIL import Image
|
| 45 |
+
|
| 46 |
+
srcs = sorted((REPO / "media").glob("*.png"))
|
| 47 |
+
ims = []
|
| 48 |
+
for p in srcs:
|
| 49 |
+
with Image.open(p) as im:
|
| 50 |
+
ims.append(im.convert("RGB"))
|
| 51 |
+
ims += [im.transpose(Image.FLIP_LEFT_RIGHT) for im in ims] # 16 distinct real pictures
|
| 52 |
+
out = []
|
| 53 |
+
for i, im in enumerate(ims):
|
| 54 |
+
if kind == "u8":
|
| 55 |
+
out.append(np.array(im.resize((448, 448), Image.BILINEAR), dtype=np.uint8))
|
| 56 |
+
elif kind in ("pil", "batch"):
|
| 57 |
+
out.append(im)
|
| 58 |
+
elif kind == "f32":
|
| 59 |
+
out.append(np.asarray(im, dtype=np.float32) / 255.0)
|
| 60 |
+
elif kind in ("png", "jpg"):
|
| 61 |
+
f = tmp / f"im{i}.{kind}"
|
| 62 |
+
im.save(f, quality=90) if kind == "jpg" else im.save(f)
|
| 63 |
+
out.append(str(f))
|
| 64 |
+
else:
|
| 65 |
+
raise SystemExit(f"unknown --input {kind}")
|
| 66 |
+
return out
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _boxes(rng, n):
|
| 70 |
+
bs = []
|
| 71 |
+
for _ in range(n):
|
| 72 |
+
w, h = rng.uniform(0.08, 0.2), rng.uniform(0.08, 0.2)
|
| 73 |
+
x, y = rng.uniform(0, 1 - w), rng.uniform(0, 1 - h)
|
| 74 |
+
bs.append([x, y, x + w, y + h])
|
| 75 |
+
return bs
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def main() -> None:
|
| 79 |
+
ap = argparse.ArgumentParser()
|
| 80 |
+
ap.add_argument("--heads", type=int, default=1)
|
| 81 |
+
ap.add_argument("--input", default="u8")
|
| 82 |
+
ap.add_argument("--steady", type=int, default=96)
|
| 83 |
+
ap.add_argument("--out", default="")
|
| 84 |
+
ap.add_argument("--kwargs", default="{}", help="JSON kwargs for from_pretrained")
|
| 85 |
+
args = ap.parse_args()
|
| 86 |
+
|
| 87 |
+
import numpy as np
|
| 88 |
+
|
| 89 |
+
tmp = Path(tempfile.mkdtemp(prefix="gaze_fc_"))
|
| 90 |
+
images = _images(args.input, tmp)
|
| 91 |
+
rng = np.random.default_rng(1000 + args.heads)
|
| 92 |
+
boxes = [_boxes(rng, args.heads) for _ in range(len(images))]
|
| 93 |
+
t_import0 = time.perf_counter()
|
| 94 |
+
from gaze_lle import GazeLLE
|
| 95 |
+
|
| 96 |
+
t_import = time.perf_counter() - t_import0
|
| 97 |
+
t = time.perf_counter()
|
| 98 |
+
model = GazeLLE.from_pretrained(**json.loads(args.kwargs))
|
| 99 |
+
t_fp = time.perf_counter() - t
|
| 100 |
+
lat, outs = [], []
|
| 101 |
+
|
| 102 |
+
def call(i):
|
| 103 |
+
im, bb = images[i % len(images)], boxes[i % len(boxes)]
|
| 104 |
+
t = time.perf_counter()
|
| 105 |
+
if args.input == "batch":
|
| 106 |
+
j = [(i * 4 + k) % len(images) for k in range(4)]
|
| 107 |
+
r = model.predict_batch([images[k] for k in j], [boxes[k] for k in j])
|
| 108 |
+
_ = [x.gaze_xy for x in r]
|
| 109 |
+
dt = time.perf_counter() - t
|
| 110 |
+
return dt, r
|
| 111 |
+
r = model(im, bb)
|
| 112 |
+
_ = r.gaze_xy
|
| 113 |
+
return time.perf_counter() - t, [r]
|
| 114 |
+
|
| 115 |
+
for i in range(10):
|
| 116 |
+
dt, r = call(i)
|
| 117 |
+
lat.append(dt * 1e3)
|
| 118 |
+
outs.append([(x.heatmap.clone(), x.inout.clone()) for x in r])
|
| 119 |
+
steady = [call(10 + i)[0] * 1e3 for i in range(args.steady)]
|
| 120 |
+
med = statistics.median(steady)
|
| 121 |
+
# same picture as call 1 (image sizes differ, so host resize / decode time differs per picture)
|
| 122 |
+
same = [steady[i] for i in range(len(steady)) if (10 + i) % len(images) == 0]
|
| 123 |
+
same_med = statistics.median(same) if same else float("nan")
|
| 124 |
+
rec = dict(heads=args.heads, input=args.input, kwargs=json.loads(args.kwargs), import_s=round(t_import, 2),
|
| 125 |
+
from_pretrained_s=round(t_fp, 2), call1_ms=round(lat[0], 3), call2_ms=round(lat[1], 3),
|
| 126 |
+
call10_ms=round(lat[9], 3), steady_median_ms=round(med, 3), steady_min_ms=round(min(steady), 3),
|
| 127 |
+
first_over_median=round(lat[0] / med, 3),
|
| 128 |
+
same_image_median_ms=round(same_med, 3), first_over_same_image=round(lat[0] / same_med, 3), calls_ms=[round(x, 3) for x in lat],
|
| 129 |
+
info_buckets=model.info().get("fused", {}).get("trace_buckets"))
|
| 130 |
+
model.close()
|
| 131 |
+
if args.out:
|
| 132 |
+
import torch
|
| 133 |
+
|
| 134 |
+
torch.save(outs, args.out)
|
| 135 |
+
print("RESULT " + json.dumps(rec), flush=True)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
if __name__ == "__main__":
|
| 139 |
+
main()
|