File size: 4,975 Bytes
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
31ffdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b01b36
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
# SPDX-License-Identifier: Apache-2.0
"""KITScenes evaluation on the device (bin/devrun): the dumped lane samples (``tools/dump_inputs.py``) through the
traced stateful runner, one stream per partition, the host planner and rollout.

    bin/devrun python -m tt_autoe2e.tests.dev_eval --inputs /ae2e/dev_inputs --out /ae2e/dev_eval/<run> \
        [--parts ...] [--max-samples N]

Per partition ``<out>/<part>.npz``: ``frames``, ``controls`` [N, 64, 2], ``xy`` [N, 64, 2] (upstream rollout),
``target_xy``, ``target_valid``, ``v0``; ``<out>/<part>.json``: timing. A sample marked ``restart`` primes the FPN
ring from its 7 history frames first (``push``), as upstream's cache does after a gap.
"""
from __future__ import annotations

import argparse
import glob
import json
import os
import time

import numpy as np

CKPT = "/ae2e/881e6a8367746da1eaae044a68077d0e7ce6fc1b/models/kitscenes-epoch-5/checkpoint.pt"


def bits_to_f32(a: np.ndarray) -> np.ndarray:
    return (np.asarray(a, np.uint16).astype(np.uint32) << 16).view(np.float32)


def main(argv=None) -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--inputs", default="/ae2e/dev_inputs")
    ap.add_argument("--out", required=True)
    ap.add_argument("--parts", nargs="*", default=None)
    ap.add_argument("--max-samples", type=int, default=0)
    args = ap.parse_args(argv)
    import torch

    from ..host import head as H
    from ..host.geometry import bev_geometry, frame_geometry
    from ..reference.tree import load_tree
    from ..tt.fusion import FRONT_CAP
    from ..tt.image import state_dict_of
    from ..tt.runner import DEVICE_DEFAULTS, AutoE2EDevice
    from ..ttaw.device import DeviceConfig, close_device

    torch.set_num_threads(8)
    tree = load_tree(CKPT)
    state = state_dict_of(tree)
    parts = args.parts or sorted(os.path.basename(os.path.dirname(p))
                                 for p in glob.glob(os.path.join(args.inputs, "*", "index.json")))
    os.makedirs(args.out, exist_ok=True)
    dev = DeviceConfig(**DEVICE_DEFAULTS).open()
    try:
        m = AutoE2EDevice(dev, tree)
        t = time.perf_counter()
        m.capture()
        cap_s = time.perf_counter() - t
        for name in parts:
            dst = os.path.join(args.out, f"{name}.npz")
            if os.path.exists(dst):
                continue
            index = json.load(open(os.path.join(args.inputs, name, "index.json")))
            if args.max_samples:
                index = index[:args.max_samples]
            rows = {k: [] for k in ("frames", "controls", "xy", "target_xy", "target_valid", "v0")}
            tm = {"prime_s": 0.0, "host_s": 0.0, "device_s": 0.0, "planner_s": 0.0, "samples": 0, "primes": 0}
            for item in index:
                z = np.load(os.path.join(args.inputs, name, f"{item['frame']:06d}.npz"))
                if "hist" in z.files:
                    t = time.perf_counter()
                    for k in range(z["hist"].shape[0]):
                        m.push(bits_to_f32(z["hist"][k]))
                    tm["prime_s"] += time.perf_counter() - t
                    tm["primes"] += 1
                t = time.perf_counter()
                geos = [bev_geometry(z["P_hist"][k], 512) for k in range(7)] + [bev_geometry(z["P"], 512)]
                gf = frame_geometry(z["P_front"], 1024, r_cap=FRONT_CAP, k_cams=1)
                nav, _ = H.navigation(state, z["map_context"], z["route_mask"], bool(z["map_valid"]),
                                      bool(z["route_valid"]))
                t1 = time.perf_counter()
                fused = m.step(bits_to_f32(z["cams"]), bits_to_f32(z["front"]), geos, gf,
                               np.ascontiguousarray(nav.reshape(256, -1).T))
                t2 = time.perf_counter()
                ctrl = H.planner(state, fused, H.normalize_egomotion(z["ego"]), z["visual_history"])
                t3 = time.perf_counter()
                tm["host_s"] += t1 - t
                tm["device_s"] += t2 - t1
                tm["planner_s"] += t3 - t2
                tm["samples"] += 1
                xy, _, _ = H.rollout(ctrl, float(z["v0"]))
                rows["frames"].append(int(z["frame"]))
                rows["controls"].append(ctrl.astype(np.float32))
                rows["xy"].append(xy.astype(np.float32))
                rows["target_xy"].append(z["target_xy"])
                rows["target_valid"].append(z["target_valid"])
                rows["v0"].append(float(z["v0"]))
            np.savez(dst, **{k: np.asarray(v) for k, v in rows.items()})
            tm["capture_s"] = cap_s
            with open(os.path.join(args.out, f"{name}.json"), "w") as f:
                json.dump(tm, f, indent=1)
            print(f"{name}: {tm['samples']} samples, device {tm['device_s'] / max(tm['samples'], 1):.2f} s/sample",
                  flush=True)
        m.release()
    finally:
        close_device(dev)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())