File size: 11,897 Bytes
c147de1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# SPDX-License-Identifier: Apache-2.0
"""Python API: the VisionPilot networks on one Tenstorrent Blackhole p150.

    from tt_visionpilot.api import AutoSteer, AutoSpeed, AutoDrive

    with AutoSteer.from_pretrained() as model:          # weights -> device -> plan -> trace captured
        out = model(images=[{"camera": "front", "path": "frame.jpg"}])
    print(out.to_dict())                                 # the same JSON as POST /predict

Each class serves one published ONNX file (the file VisionPilot itself loads; vision_pilot 87a82ec8
``VisionPilot/modules/models/weights``). At load the file is folded for batch 1 (onnxruntime, basic level), the
device plan is built from the folded graph (``plan.py``), the input stem rewritten for 4 x 4 space-to-depth uploads
(``stem.py``) and the frame captured as one trace (``tt/runner.py``). A call: host pre-processing as VisionPilot
(``host/prep.py``) -> upload + replay + one packed read -> the graph's last ops on the host -> VisionPilot's
decoding (``outputs.py``).
"""
from __future__ import annotations

import hashlib
import os
from pathlib import Path
from typing import Any, Dict, Optional

import numpy as np

from . import io as tio
from .models import NETWORKS
from .outputs import AutoDriveOutput, AutoSpeedOutput, AutoSteerOutput, autospeed_decode
from .ttaw.api_base import ModelBase

__all__ = ["AutoSteer", "AutoSpeed", "AutoDrive", "DEVICE_DEFAULTS", "fold_onnx"]

DEVICE_DEFAULTS: Dict[str, Any] = {"num_command_queues": 1, "l1_small_size": 32768, "trace_region_size": 96 << 20}

# sha256 of the published files (vision_pilot 87a82ec8 VisionPilot/modules/models/weights == the README's Google
# Drive files; AutoSpeed also == AutowareFoundation/auto_speed models/autospeed_2_fp32.onnx)
ONNX_SHA256 = {
    "autosteer": "770d26f431467bbcc7fe3e794411cac36d8dfbd1658e4eb4a37d48342db7cbf6",
    "autospeed": "adff7dd9fa9c2d306d9228a87edcf2ae256edbdc9e4b9541fd471880aa5c1451",
    "autodrive": "196a82289ba7d96f574cc4dfa8815dadb9f104397c7c2bec7c98333e5ee8762d",
}


def _sha256(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def fold_onnx(src: Path, cache_dir: Optional[Path] = None) -> Path:
    """The published file with the batch fixed to 1 and constants folded (onnxruntime basic level), cached next to
    the HF cache by content hash. A file ``folded/<name>`` next to ``src`` (made by ``tools/fold.py``) is used
    when present."""
    pre = src.parent / "folded" / src.name
    if pre.exists():
        return pre
    digest = _sha256(src)[:16]
    cache = Path(cache_dir or os.environ.get("VP_FOLD_CACHE") or Path.home() / ".cache" / "tt_visionpilot")
    cache.mkdir(parents=True, exist_ok=True)
    dst = cache / f"{src.stem}.{digest}.folded.onnx"
    if dst.exists():
        return dst
    import onnx
    import onnxruntime as ort

    m = onnx.load(str(src))
    for v in list(m.graph.input) + list(m.graph.output):
        dims = v.type.tensor_type.shape.dim
        if dims and dims[0].dim_param:
            dims[0].dim_value = 1
    tmp = dst.with_suffix(".b1.tmp.onnx")
    onnx.save(m, str(tmp))
    so = ort.SessionOptions()
    so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
    so.optimized_model_filepath = str(dst)
    so.intra_op_num_threads = 4
    ort.InferenceSession(str(tmp), so, providers=["CPUExecutionProvider"])
    tmp.unlink()
    return dst


class _VisionPilotNet(ModelBase):
    NETWORK = ""
    WEIGHTS_FILE = ""
    VARIANTS = ("default",)
    DEFAULT_VARIANT = "default"
    INPUT_KIND = "camera"
    REQUIRE_CALIBRATION = False
    WEIGHTS_LICENSE = "Apache-2.0 (vision_pilot README: the complete codebase, including AI model weights)"
    DEVICE_DEFAULTS = DEVICE_DEFAULTS

    def _build(self) -> None:
        from .graph import Graph
        from .tt.runner import NetRunner

        src = Path(self.weights_path) / self.WEIGHTS_FILE
        if not src.exists():
            raise FileNotFoundError(f"{src}: weights file missing")
        digest = _sha256(src)
        if digest != ONNX_SHA256[self.NETWORK] and os.environ.get("VP_ALLOW_OTHER_WEIGHTS") != "1":
            raise ValueError(f"{src.name}: sha256 {digest[:16]}... is not the published file "
                             f"({ONNX_SHA256[self.NETWORK][:16]}...); VP_ALLOW_OTHER_WEIGHTS=1 to run it anyway")
        self.spec = NETWORKS[self.NETWORK]
        self.graph = Graph(fold_onnx(src))
        self.net = NetRunner(self.device, self.spec, self.graph)
        self.weights_sha256 = digest

    def _warm_one(self, variant: Any) -> None:
        self.net.capture()

    def _images(self, images: Any, n: int):
        cams = tio.load_cameras(images, require_calibration=False)
        if len(cams) != n:
            raise tio.InputError(f"{self.MODEL_NAME} takes {n} image(s), got {len(cams)}")
        return cams

    def _forward(self, prepared: Dict[str, Any]) -> Dict[str, np.ndarray]:
        return self.net.run_device(prepared["images"])

    def _release(self) -> None:
        net = getattr(self, "net", None)
        if net is not None:
            net.release()

    def extra_info(self) -> Dict[str, Any]:
        info: Dict[str, Any] = {"network": self.NETWORK}
        if getattr(self, "net", None) is not None:
            info["plan"] = self.net.plan.summary()
            info["weights_sha256"] = self.weights_sha256
            info["trace"] = self.net.runner.describe()
        return info


class AutoSteer(_VisionPilotNet):
    """AutoSteer 2.0 (ego path) on one p150."""

    MODEL_NAME = "auto_steer-p150"
    ENV_PREFIX = "AUTOSTEER"
    NETWORK = "autosteer"
    WEIGHTS_FILE = "weights/autosteer_fp32.onnx"
    DEFAULT_REPO = "changh95/auto_steer-p150"
    DEFAULT_REVISION = "c6f1e132e5ddc084d7ab2f31a5f6944be830f688"
    ALLOW_PATTERNS = ["weights/*"]
    LABELS = ()

    def _prepare(self, points: Any = None, *, images: Any = None, **_: Any) -> Dict[str, Any]:
        from .host.prep import front_image

        if points is not None:
            raise tio.InputError("AutoSteer takes one front camera image, not points")
        cam = self._images(images, 1)[0]
        img, geom = front_image(cam.image)
        return {"images": {"input": img}, "geometry": geom, "camera": cam.name}

    def _postprocess(self, raw, prepared, params) -> AutoSteerOutput:
        outs = self.net.plan.run_tail(raw)
        return AutoSteerOutput(outs["lane_value"], outs["height"], model=self.MODEL_NAME,
                               frame_id=prepared["camera"] or "camera", meta={"geometry": prepared["geometry"]})


class AutoSpeed(_VisionPilotNet):
    """AutoSpeed 2.0 (closest in-path object detection) on one p150."""

    MODEL_NAME = "auto_speed-p150"
    ENV_PREFIX = "AUTOSPEED"
    NETWORK = "autospeed"
    WEIGHTS_FILE = "models/autospeed_2_fp32.onnx"
    DEFAULT_REPO = "AutowareFoundation/auto_speed"
    DEFAULT_REVISION = "cee87c3a001cb1a0cbf0ffcb3f2121e4ef4935b7"
    ALLOW_PATTERNS = ["models/autospeed_2_fp32.onnx", "README.md"]
    WEIGHTS_LICENSE = "Apache-2.0 (AutowareFoundation/auto_speed model card)"
    LABELS = AutoSpeedOutput.LABELS
    RUNTIME_PARAMS = {"conf_threshold": (float, 0.0, 1.0, 0.6), "iou_threshold": (float, 0.0, 1.0, 0.45)}

    def _prepare(self, points: Any = None, *, images: Any = None, **_: Any) -> Dict[str, Any]:
        from .host.prep import front_image

        if points is not None:
            raise tio.InputError("AutoSpeed takes one front camera image, not points")
        cam = self._images(images, 1)[0]
        img, geom = front_image(cam.image)
        return {"images": {"input": img}, "geometry": geom, "camera": cam.name}

    def _postprocess(self, raw, prepared, params) -> AutoSpeedOutput:
        outs = self.net.plan.run_tail(raw)
        b, s, c, p = autospeed_decode(outs["output"], float(params["conf_threshold"]), float(params["iou_threshold"]))
        return AutoSpeedOutput(b, s, c, p, geometry=prepared["geometry"], model=self.MODEL_NAME,
                               frame_id=prepared["camera"] or "camera")


class AutoDrive(_VisionPilotNet):
    """AutoDrive (distance to the closest in-path object, road curvature, its presence) on one p150.

    Two frames ``images=[{"camera": "prev", ...}, {"camera": "curr", ...}]``: both backbones run (stateless). Or
    one frame per call with ``stream={"id": ..., "reset": ...}``: the server keeps the previous frame's backbone
    output on the device, so each frame runs one backbone (4.5 ms instead of 8 ms on the p150); the first frame of a
    stream (new id or ``reset``) returns ``ready: false``, as VisionPilot returns nothing on its first frame. Frames
    are either already warped (1024 x 512) or raw with ``homography`` (3x3, raw pixel -> warped 1024 x 512,
    VisionPilot's ``C``)."""

    MODEL_NAME = "auto_drive-p150"
    ENV_PREFIX = "AUTODRIVE"
    NETWORK = "autodrive"
    WEIGHTS_FILE = "weights/autodrive_fp32.onnx"
    DEFAULT_REPO = "changh95/auto_drive-p150"
    DEFAULT_REVISION = "541c0fdd0e09f5967f05918a0442c6b7f2bb992e"
    ALLOW_PATTERNS = ["weights/*"]
    INPUT_KIND = "multicam"
    # no CAMERA_ORDER: the server would then demand both frames on every request; _prepare orders a pair itself and
    # takes a single frame as one frame of a stream
    CAMERA_ORDER = ()
    PAIR_ORDER = ("prev", "curr")
    EXTRA_INPUTS = ("homography",)

    def _prepare(self, points: Any = None, *, images: Any = None, homography: Any = None, stream: Any = None,
                 **_: Any) -> Dict[str, Any]:
        from .host.prep import warped_image

        if points is not None:
            raise tio.InputError("AutoDrive takes two camera frames (prev, curr), or one frame of a stream, not points")
        cams = tio.load_cameras(images, require_calibration=False)
        if len(cams) == 1:
            mode = "stream"
        else:
            cams = tio.load_cameras(images, require_calibration=False, order=list(self.PAIR_ORDER))
            mode = "pair"
        H = None
        if homography is not None:
            H = np.asarray(homography, np.float64)
            if H.size != 9 or not np.all(np.isfinite(H)):
                raise tio.InputError("homography must be 9 finite numbers (3x3, row-major)")
        try:
            warped = [warped_image(c.image, H) for c in cams]
        except ValueError as e:
            raise tio.InputError(str(e)) from None
        if mode == "pair":
            return {"mode": mode, "images": {"image_prev": warped[0], "image_curr": warped[1]}, "camera": "curr"}
        sid = str((stream or {}).get("id") or "default")
        fresh = bool((stream or {}).get("reset")) or sid != getattr(self, "_stream_id", None)
        return {"mode": mode, "image": warped[0], "fresh": fresh, "stream_id": sid, "camera": cams[0].name}

    def _forward(self, prepared: Dict[str, Any]) -> Any:
        if prepared["mode"] == "pair":
            return self.net.plan.run_tail(self.net.run_device(prepared["images"]))
        out = self.net.stream(prepared["image"], fresh=prepared["fresh"])
        self._stream_id = prepared["stream_id"]
        return out

    def _postprocess(self, raw, prepared, params) -> AutoDriveOutput:
        meta = {"mode": prepared["mode"]}
        if prepared["mode"] == "stream":
            meta.update({"stream_id": prepared["stream_id"], "fresh": prepared["fresh"]})
        if raw is None:
            return AutoDriveOutput(None, None, None, model=self.MODEL_NAME, frame_id="camera", meta=meta)
        return AutoDriveOutput(raw["distance"].reshape(-1)[0], raw["curvature"].reshape(-1)[0],
                               raw["flag_logit"].reshape(-1)[0], model=self.MODEL_NAME, frame_id="camera", meta=meta)


MODELS = {"autosteer": AutoSteer, "autospeed": AutoSpeed, "autodrive": AutoDrive}