Download code/tt_autoe2e/api.py from changh95/auto_e2e-p150: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/changh95/auto_e2e-p150/resolve/main/code/tt_autoe2e/api.py
- Command line
-
hf download hf://changh95/auto_e2e-p150/code/tt_autoe2e/api.py
-
curl -L -o api.py https://huggingface.co/changh95/auto_e2e-p150/resolve/main/code/tt_autoe2e/api.py
12.9 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """``AutoE2E``: the Python API of the AutoE2E (Reactive v1.0, KITScenes checkpoint) port on one p150. | |
| from tt_autoe2e.api import AutoE2E | |
| model = AutoE2E.from_pretrained() # AutowareFoundation/auto_e2e at the pinned commit | |
| out = model(images={"front": rgb, ...}, calibration={"cameras": {...}}, | |
| stream={"id": "car0", "reset": False, "T_world_from_ego": pose}, | |
| inputs={"egomotion_history": ego, "map_context": raster, "route_mask": route}) | |
| out.poses # [64, 6]: x, y, yaw, speed, accel, curvature (10 Hz, 6.4 s) | |
| One call = one step of a stream on the model's 500 ms history grid (call it at 2 Hz per stream). The device keeps | |
| the FPN pyramids of the stream's last 7 steps; the host keeps their projection matrices and ego poses, so the | |
| history projections (current ego -> each past image) are ``P_k inv(T_world_from_ego_k) T_world_from_ego_now``, as | |
| upstream builds them. A new stream id or ``reset`` starts with the current step copied into all 7 history slots | |
| (history projections = the current ones): upstream's no-history behaviour (the current BEV repeated); ``meta. | |
| history_steps`` says how many real past steps the answer used. | |
| Inputs (per step): | |
| - ``images``: the 6 cameras ``front, front_left, front_right, rear_left, rear, rear_right`` (RGB, any size); the | |
| front camera is resized to 1024 x 1024 (the native-front branch) and its 512 view taken from that with an | |
| antialiased bilinear resize, the others resized to 512 x 512 (PIL bilinear, anisotropic: upstream's KITScenes | |
| loader); | |
| - ``calibration``: per camera ``intrinsics`` (K of the image as sent) and ``T_ref_from_camera`` (camera -> the | |
| model's ego frame: KITScenes' reference frame, x forward, y left, z up, origin 2.1 m above the road); | |
| - ``stream``: ``id``, ``reset``, ``T_world_from_ego`` (4 x 4); | |
| - ``inputs``: ``egomotion_history`` [256] (64 x [speed m/s, acceleration m/s^2, yaw rate rad/s, curvature 1/m], | |
| 10 Hz, oldest first, ending 0.1 s before now; the KITScenes policy zeroes the last acceleration), optional | |
| ``map_context`` [14, 450, 300] and ``route_mask`` [2, 450, 300] (upstream's navigation rasters: 0.4 m/px, ego FLU, | |
| rows front -> rear; absent = invalid, the model then runs without them). | |
| """ | |
| from __future__ import annotations | |
| import collections | |
| import hashlib | |
| from typing import Any, Dict, Mapping, Optional, Sequence | |
| import numpy as np | |
| from .ttaw import io as tio | |
| from .ttaw.api_base import ModelBase | |
| from .ttaw.outputs import Trajectory | |
| CKPT = "models/kitscenes-epoch-5/checkpoint.pt" | |
| CALIB_DIR = __import__("pathlib").Path(__file__).resolve().parent / "calib" | |
| CKPT_SHA256 = "120a21639d9767d512eea645be0a83b01476c9e0366a8b957ac51b7ead1bd762" | |
| COLUMNS = ("x", "y", "yaw", "speed", "accel", "curvature") | |
| IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], np.float32) | |
| IMAGENET_STD = np.array([0.229, 0.224, 0.225], np.float32) | |
| def _sha256(path) -> str: | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| while chunk := f.read(8 << 20): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def resize_rgb(rgb: np.ndarray, size: int) -> np.ndarray: | |
| """PIL bilinear resize to ``size`` x ``size`` (uint8 RGB), as upstream's KITScenes loader.""" | |
| from PIL import Image | |
| return np.asarray(Image.fromarray(np.asarray(rgb, np.uint8)).resize((size, size), Image.Resampling.BILINEAR), | |
| np.uint8) | |
| def normalized(rgb: np.ndarray) -> np.ndarray: | |
| """uint8 HWC -> the loader's ImageNet-normalised CHW float32.""" | |
| x = np.asarray(rgb, np.float32).transpose(2, 0, 1) / np.float32(255.0) | |
| return (x - IMAGENET_MEAN.reshape(3, 1, 1)) / IMAGENET_STD.reshape(3, 1, 1) | |
| def front_views(rgb: np.ndarray): | |
| """The front camera -> (1024 tile, its 512 view) normalised CHW: PIL bilinear to 1024, then | |
| ``F.interpolate(bilinear, antialias=True)`` to 512 (upstream ``pre_extracted.py``).""" | |
| import torch | |
| import torch.nn.functional as F | |
| t1024 = normalized(resize_rgb(rgb, 1024)) | |
| t512 = F.interpolate(torch.from_numpy(t1024)[None], size=(512, 512), mode="bilinear", align_corners=False, | |
| antialias=True)[0].numpy() | |
| return t1024, t512 | |
| def projection(K: np.ndarray, T_ref_from_camera: np.ndarray, wh, size: int) -> np.ndarray: | |
| """ego -> pixels of the ``size`` x ``size`` model input: ``diag(size / W, size / H, 1) K inv(T)[:3]``.""" | |
| s = np.diag([size / float(wh[0]), size / float(wh[1]), 1.0]) | |
| return (s @ np.asarray(K, np.float64) @ np.linalg.inv(np.asarray(T_ref_from_camera, np.float64))[:3]).astype( | |
| np.float64) | |
| class AutoE2E(ModelBase): | |
| MODEL_NAME = "auto_e2e-p150" | |
| ENV_PREFIX = "AUTOE2E" | |
| DEFAULT_REPO = "AutowareFoundation/auto_e2e" | |
| DEFAULT_REVISION = "881e6a8367746da1eaae044a68077d0e7ce6fc1b" | |
| ALLOW_PATTERNS = [CKPT, "README.md"] | |
| WEIGHTS_LICENSE = "CC BY-NC-SA 4.0 (AutowareFoundation/auto_e2e model card)" | |
| INPUT_KIND = "multicam" | |
| CAMERA_ORDER = ("front", "front_left", "front_right", "rear_left", "rear", "rear_right") | |
| REQUIRE_CALIBRATION = True | |
| # named inputs, checked in _prepare (the rasters are optional, so no INPUT_SCHEMA: it makes every name required) | |
| INPUT_ARRAYS = {"egomotion_history": ((256,), "float32"), "map_context": ((14, None, None), "float32"), | |
| "route_mask": ((2, None, None), "float32")} | |
| DEVICE_DEFAULTS = {"num_command_queues": 1, "trace_region_size": 768 << 20, "l1_small_size": 32768} | |
| # ------------------------------------------------------------------ build | |
| def _build(self) -> None: | |
| from .reference.tree import load_tree | |
| from .tt.image import state_dict_of | |
| from .tt.runner import AutoE2EDevice | |
| path = self.weights_path / CKPT | |
| digest = _sha256(path) | |
| if digest != CKPT_SHA256: | |
| raise ValueError(f"{path}: sha256 {digest}, expected {CKPT_SHA256}") | |
| self.tree = load_tree(str(path)) | |
| self.state = state_dict_of(self.tree) | |
| self.dev = AutoE2EDevice(self.device, self.tree) | |
| self.stream_id: Optional[str] = None | |
| self.history: collections.deque = collections.deque(maxlen=7) # (P [6, 3, 4], T_world_from_ego) | |
| self.real_steps = 0 | |
| def _pool(self): | |
| if getattr(self, "_executor", None) is None: | |
| from concurrent.futures import ThreadPoolExecutor | |
| import os | |
| n = int(os.environ.get("AE_HOST_THREADS", "8")) | |
| self._executor = ThreadPoolExecutor(max_workers=n, thread_name_prefix="autoe2e-host") | |
| return self._executor | |
| def _warm_one(self, variant: Any) -> None: | |
| self.dev.capture() | |
| def default_warmup_variants(self): | |
| return ["default"] | |
| # ------------------------------------------------------------------ host | |
| def _prepare(self, *, images: Any = None, calibration: Any = None, stream: Optional[Mapping] = None, | |
| inputs: Any = None, **_: Any) -> Dict[str, Any]: | |
| from .host import head as H | |
| from .host.geometry import bev_geometry, frame_geometry | |
| from .tt.fusion import FRONT_CAP | |
| from .tt.image import backbone_input | |
| cams = tio.load_cameras(images, calibration, order=self.CAMERA_ORDER, require_calibration=True, | |
| calib_dir=CALIB_DIR) | |
| if inputs is not None and not (isinstance(inputs, Mapping) and all(isinstance(v, np.ndarray) | |
| for v in inputs.values())): | |
| inputs = tio.load_named_arrays(inputs, None) | |
| inputs = dict(inputs or {}) | |
| if "egomotion_history" not in inputs: | |
| raise tio.InputError("inputs.egomotion_history [256] is required") | |
| given = {k: inputs[k] for k in self.INPUT_ARRAYS if k in inputs} | |
| unknown = sorted(set(inputs) - set(self.INPUT_ARRAYS)) | |
| if unknown: | |
| raise tio.InputError(f"inputs: unexpected {unknown} (expected {sorted(self.INPUT_ARRAYS)})") | |
| inputs = tio.check_named_arrays(given, {k: self.INPUT_ARRAYS[k] for k in given}) | |
| stream = dict(stream or {}) | |
| sid = str(stream.get("id", "default")) | |
| reset = bool(stream.get("reset", False)) or sid != self.stream_id | |
| pose = np.asarray(stream.get("T_world_from_ego", np.eye(4)), np.float64).reshape(4, 4) | |
| tiles = [] | |
| P = np.zeros((6, 3, 4), np.float64) | |
| for i, cam in enumerate(cams): | |
| h, w = cam.image.shape[:2] | |
| if i == 0: | |
| t1024, t512 = front_views(cam.image) | |
| P_front = projection(cam.intrinsics, cam.T_ref_from_camera, (w, h), 1024)[None] | |
| tiles.append(t512) | |
| else: | |
| tiles.append(normalized(resize_rgb(cam.image, 512))) | |
| P[i] = projection(cam.intrinsics, cam.T_ref_from_camera, (w, h), 512) | |
| cams_in = backbone_input(np.stack(tiles)) | |
| front_in = backbone_input(t1024[None]) | |
| hist = [(P, pose)] * 7 if reset else list(self.history) | |
| P_hist = [Pk @ (np.linalg.inv(Tk) @ pose) for Pk, Tk in hist] | |
| mc, rm = inputs.get("map_context"), inputs.get("route_mask") | |
| map_valid, route_valid = mc is not None, rm is not None | |
| mc = np.zeros((14, 450, 300), np.float32) if mc is None else np.asarray(mc, np.float32) | |
| rm = np.zeros((2, mc.shape[1], mc.shape[2]), np.float32) if rm is None else np.asarray(rm, np.float32) | |
| # the geometry of the 9 frames and the navigation encoder are independent: run them concurrently (torch / | |
| # numpy release the GIL), the navigation encoder first since it is the longest | |
| pool = self._pool() | |
| def nav_rows(): | |
| import torch | |
| nav, _ = H.navigation(self.state, mc, rm, map_valid, route_valid) | |
| # [Q, 256] bf16 rows for the device, converted here (on the pool) rather than in the upload | |
| return torch.from_numpy(np.ascontiguousarray(nav.reshape(256, -1).T)).to(torch.bfloat16) | |
| nav_f = pool.submit(nav_rows) | |
| # one geometry per distinct matrix set (after a reset the 7 history frames repeat the current one) | |
| mats = [p.astype(np.float32) for p in P_hist + [P]] | |
| uniq: Dict[bytes, Any] = {} | |
| for m in mats: | |
| if m.tobytes() not in uniq: | |
| uniq[m.tobytes()] = pool.submit(bev_geometry, m, 512) | |
| front_f = pool.submit(frame_geometry, P_front.astype(np.float32), 1024, r_cap=FRONT_CAP, k_cams=1) | |
| geos = [uniq[m.tobytes()].result() for m in mats] | |
| geo_front = front_f.result() | |
| ego = np.asarray(inputs["egomotion_history"], np.float32).reshape(64, 4).copy() | |
| ego[-1, 1] = 0.0 # the KITScenes policy: mask the latest history acceleration | |
| return {"cams": cams_in, "front": front_in, "geos": geos, "geo_front": geo_front, | |
| "nav_f": nav_f, "ego": ego.reshape(-1), | |
| "v0": float(ego[-1, 0]), "reset": reset, "sid": sid, "P": P, "pose": pose, | |
| "map_valid": map_valid, "route_valid": route_valid} | |
| def _forward(self, prep: Dict[str, Any]) -> Any: | |
| if prep["reset"]: | |
| for _ in range(7): | |
| self.dev.push(prep["cams"]) | |
| self.stream_id = prep["sid"] | |
| self.history.clear() | |
| self.history.extend([(prep["P"], prep["pose"])] * 7) | |
| self.real_steps = 0 | |
| # step_a runs on the device while the navigation BEV finishes on the host pool | |
| self.dev.step_begin(prep["cams"], prep["front"], prep["geos"], prep["geo_front"]) | |
| fused = self.dev.step_end(prep["nav_f"].result()) | |
| history_steps = self.real_steps | |
| self.history.append((prep["P"], prep["pose"])) | |
| self.real_steps = min(self.real_steps + 1, 7) | |
| return fused, history_steps | |
| def _postprocess(self, raw: Any, prep: Dict[str, Any], params: Dict[str, Any]) -> Trajectory: | |
| from .host import head as H | |
| fused, history_steps = raw | |
| ctrl = H.planner(self.state, fused, H.normalize_egomotion(prep["ego"])) | |
| xy, heading, speed = H.rollout(ctrl, prep["v0"]) | |
| poses = np.concatenate([xy, heading[:, None], speed[:, None], ctrl], axis=1) | |
| return Trajectory(poses=poses, columns=COLUMNS, model=self.MODEL_NAME, frame_id="ego", | |
| meta={"history_steps": int(history_steps), "stream_id": prep["sid"], | |
| "reset": bool(prep["reset"]), "map_valid": prep["map_valid"], | |
| "route_valid": prep["route_valid"], "dt_s": 0.1}) | |
| def _release(self) -> None: | |
| ex = getattr(self, "_executor", None) | |
| if ex is not None: | |
| ex.shutdown(wait=True) | |
| self._executor = None | |
| dev = getattr(self, "dev", None) | |
| if dev is not None: | |
| dev.release() | |