File size: 7,852 Bytes
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""The upstream AutoE2E model (autowarefoundation/auto_e2e, Apache-2.0) as the reference: loading, data, one call.

The upstream repository is not vendored: ``AUTOE2E_SRC`` (default ``~/ttaw-phase0/src/auto_e2e``, commit
``4dfe81e9``) is put on ``sys.path``. The checkpoint is ``AutowareFoundation/auto_e2e`` at
:data:`WEIGHTS_REVISION`, ``models/kitscenes-epoch-5/checkpoint.pt`` (CC BY-NC-SA 4.0), loaded with
``weights_only=True`` (no pickle execution; upstream ``load_policy`` uses ``weights_only=False``).

Precision modes of :func:`predict`:

- ``fp32``: no autocast, TF32 off for matmuls and cuDNN convolutions (a true fp32 reference on CUDA or CPU);
- ``bf16``: upstream's own inference contract (``Platform/pipelines/inference.py`` ``inference_autocast``: bf16
  autocast on CUDA; projection and ``grid_sample`` stay fp32 inside the model), the operating point of the published
  KITScenes metrics.
"""
from __future__ import annotations

import contextlib
import hashlib
import os
import sys
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional, Sequence

import numpy as np

SRC = Path(os.environ.get("AUTOE2E_SRC", Path.home() / "ttaw-phase0/src/auto_e2e"))
UPSTREAM_COMMIT = "4dfe81e9"
WEIGHTS_REPO = "AutowareFoundation/auto_e2e"
WEIGHTS_REVISION = "881e6a8367746da1eaae044a68077d0e7ce6fc1b"
CHECKPOINT = "models/kitscenes-epoch-5/checkpoint.pt"
CHECKPOINT_SHA256 = "120a21639d9767d512eea645be0a83b01476c9e0366a8b957ac51b7ead1bd762"
KITSCENES = "KIT-MRT/KITScenes-Multimodal"
LANE_STRIDE = 5  # the evaluator's lanes: 500 ms history grid / 100 ms source cadence

if str(SRC) not in sys.path:
    sys.path[:0] = [str(SRC / "Model"), str(SRC)]


def sha256(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        while chunk := f.read(8 << 20):
            h.update(chunk)
    return h.hexdigest()


def checkpoint_path(weights_dir: Optional[str] = None) -> Path:
    if weights_dir:
        return Path(weights_dir) / CHECKPOINT
    from huggingface_hub import hf_hub_download

    return Path(hf_hub_download(WEIGHTS_REPO, CHECKPOINT, revision=WEIGHTS_REVISION))


def load_model(device: str = "cpu", weights_dir: Optional[str] = None, *, check_sha: bool = True):
    """``(model, config, digest, policy)``: the Reactive model rebuilt from its stage as ``load_policy`` does."""
    import torch
    from Platform.pipelines.inference import reactive_policy_kwargs
    from model_components.auto_e2e import AutoE2E
    from training.dataset_policy import training_policy_from_config

    path = checkpoint_path(weights_dir)
    digest = sha256(path) if check_sha else CHECKPOINT_SHA256
    if digest != CHECKPOINT_SHA256:
        raise ValueError(f"{path}: sha256 {digest}, expected {CHECKPOINT_SHA256}")
    ckpt = torch.load(path, map_location="cpu", weights_only=True)
    config = dict(ckpt["config"])
    model = AutoE2E(**reactive_policy_kwargs(config))
    model.load_state_dict(ckpt["model_state_dict"])
    model.eval().requires_grad_(False)
    model.to(device)
    return model, config, digest, training_policy_from_config(config, KITSCENES)


def partition_samples(partition_dir: Path) -> List[str]:
    """The sample uids of a partition directory (``<dir>/*.tar`` + ``<dir>/pool/``), in frame order."""
    import tarfile

    uids = set()
    for tar in sorted(Path(partition_dir).glob("*.tar")):
        with tarfile.open(tar) as t:
            uids.update(n.split(".", 1)[0] for n in t.getnames())
    return sorted(uids, key=lambda u: int(u.rsplit("-f", 1)[1]))


def iter_batches(partition_dir: Path, uids: Optional[Sequence[str]] = None) -> Iterator[Dict[str, Any]]:
    """Batches of one sample from the upstream loader (``make_pre_extracted_loader``, no shuffle, front FPN tile)."""
    from data_parsing.pre_extracted import make_pre_extracted_loader

    loader = make_pre_extracted_loader(str(partition_dir), batch_size=1, num_workers=0, shuffle=0,
                                       decode_future_frames=False, decode_front_camera_fpn=True,
                                       sample_uids=list(uids) if uids is not None else None)
    yield from loader


def adapt(batch: Dict[str, Any], policy: Any) -> Dict[str, Any]:
    """The KITScenes egomotion policy (zeroes the last acceleration), as the evaluator applies it."""
    from training.dataset_policy import adapt_egomotion_history

    batch = dict(batch)
    batch["egomotion_history_raw"] = batch["egomotion_history"]
    batch["egomotion_history"] = adapt_egomotion_history(batch["egomotion_history"], policy)
    return batch


def to_device(batch: Dict[str, Any], device: str) -> Dict[str, Any]:
    import torch

    return {k: (v.to(device) if isinstance(v, torch.Tensor) else v) for k, v in batch.items()}


@contextlib.contextmanager
def precision(mode: str):
    """``fp32`` (no autocast, no TF32) or ``bf16`` (upstream's CUDA contract) around :func:`predict`."""
    import torch
    import Platform.pipelines.inference as inf

    if mode not in ("fp32", "bf16"):
        raise ValueError(mode)
    saved = (inf.inference_autocast, torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32)
    try:
        torch.backends.cuda.matmul.allow_tf32 = False
        torch.backends.cudnn.allow_tf32 = False
        if mode == "fp32":
            inf.inference_autocast = lambda _device: contextlib.nullcontext()
        yield
    finally:
        inf.inference_autocast, torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 = saved


def predict(model: Any, batch: Dict[str, Any], digest: str, *, cache: Any = None) -> np.ndarray:
    """Controls ``[1, 64, 2]`` (acceleration m/s^2, curvature 1/m) from upstream ``predict_control``; with ``cache``
    (``create_stateful_camera_fpn_cache``) the evaluator's stateful lane form (stream = scene + ``frame % 5``)."""
    import torch
    from Platform.pipelines.inference import predict_control

    kw: Dict[str, Any] = {}
    if cache is not None:
        frame = int(batch["source_frame_index"][0])
        interval = int(batch["source_frame_interval_us"][0])
        kw = {"camera_fpn_cache": cache,
              "camera_fpn_stream_ids": (f"{batch['split_group_uid'][0]}:lane:{frame % LANE_STRIDE}",),
              "camera_fpn_timestamps_us": torch.tensor([frame * interval], dtype=torch.int64)}
    return predict_control(model, batch, sample_uids=[str(u) for u in batch["sample_uid"]],
                           model_artifact_id=digest, dataset_manifest_digest="local-reference", base_seed=0,
                           projection=None, geometry_type="pseudo", **kw)


def rollout(controls: np.ndarray, v0: float):
    """Upstream's semi-implicit unicycle rollout (``training/losses/control_rollout.py``): xy [64, 2], heading, speed."""
    import torch
    from training.losses.control_rollout import integrate_controls_torch

    xy, heading, speed = integrate_controls_torch(torch.as_tensor(controls, dtype=torch.float32).reshape(1, 64, 2),
                                                  torch.tensor([float(v0)], dtype=torch.float32))
    return xy[0].numpy(), heading[0].numpy(), speed[0].numpy()


HORIZONS = {"1s": 10, "2s": 20, "3s": 30, "5s": 50}


def displacement(xy: np.ndarray, target_xy: np.ndarray, valid: np.ndarray) -> Dict[str, float]:
    """ADE / FDE per horizon over the valid label steps (as the recon reference and the evaluator report them)."""
    err = np.linalg.norm(np.asarray(xy, np.float64) - np.asarray(target_xy, np.float64), axis=-1)
    valid = np.asarray(valid, bool)
    out: Dict[str, float] = {}
    for name, n in HORIZONS.items():
        v = valid[:n]
        if v.any():
            out[f"ade_{name}"] = float(err[:n][v].mean())
        if valid[n - 1]:
            out[f"fde_{name}"] = float(err[n - 1])
    return out