File size: 16,266 Bytes
2230fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18c340c
 
2230fab
 
18c340c
 
2230fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18c340c
 
2230fab
18c340c
 
 
 
 
 
2230fab
 
 
 
 
 
 
 
 
18c340c
2230fab
 
18c340c
 
 
2230fab
18c340c
 
 
 
 
 
 
2230fab
 
 
 
 
 
 
 
 
 
 
 
18c340c
 
 
 
 
 
 
 
 
 
 
 
2230fab
 
 
18c340c
2230fab
 
 
 
 
 
 
 
 
 
 
 
18c340c
2230fab
 
 
 
 
 
 
 
 
 
 
18c340c
 
2230fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18c340c
 
 
 
2230fab
 
 
 
 
 
 
 
 
 
 
 
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
263
264
265
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Stage breakdown of warm forwards: the numbers OPT_BASELINE.md / OPT_REPORT.md / the card quote.

    bin/devrun -t 900 -- python code/scripts/bench.py --iters 100 --json logs/baseline_bench.json
    bin/devrun -t 900 -- python code/scripts/bench.py --variant tiny --input a.npz --input b.npy --dispatch worker --cqs 2

For every ``--input`` cloud (default: the shipped sample ``samples/test_pcd.npz``), batch 1, after ``--warmup``
calls: ``--iters`` iterations of the served path cut into stages, each synchronised on its own (p50 / p99 / mean /
min in ms, so the rows do not add up to ``e2e`` exactly), then ``--iters`` plain ``model(points)`` calls, then
back-to-back replays:

=====================  ================================================================================================
``pre``                host pre-processing as served (``model._prepare``): decode + densification + voxelization
                       (seed-0 permutation, first 32 points per pillar) + the 9 decorated features + the canvas index
``pre.load``           the file decode alone (``ttaw.io.load_points``; a research ``.npy`` is read as x, y, z, time_lag)
``pre.densify``        the cloud handed to the voxelizer (x, y, z, time_lag; non-finite / all-zero rows dropped)
``pre.assign``         ``ttaw.voxelize.assign_pillars``: range filter, permutation, cell keys, first 32 per pillar
``pre.decorate``       ``ttaw.voxelize.decorate_pillar_features``: the (40000, 32, 9) float32 encoder input
``pre.index``          ``ttaw.voxelize.canvas_gather_index``: cell -> pillar row (the C19 gather index)
``host_in``            ``FrameStaging.write``: the kept pillars converted to bf16 in the persistent host buffers
``h2d``                upload of both trace inputs + device synchronise (``TraceRunner.upload``)
``h2d.<input>``        the upload split per input (``features`` 41 MB bf16 rows, ``canvas_index`` 0.9 MB uint32)
``trace``              one blocking replay of the whole-graph trace
``d2h``                the head read-back as served: ``TraceRunner.read`` (fp32 TILE -> untilized numpy), or with
                       ``CENTERPOINT_HOST_READBACK=tiled`` the copy into the aliased host buffer only
``d2h.copy``           the readback split: the device-to-host copy into a preallocated host tensor ...
``d2h.to_numpy``       ... and its host conversion to numpy (host untilize of the TILE rows)
``unpack``             ``TtCenterPoint.unpack``: the 15 channels -> the six head maps (C, H, W); with
                       ``CENTERPOINT_HOST_DECODE=rows`` only the ``HeadRows`` wrapper (the decode reads the rows)
``post``               host post-processing (decode, sort, circle NMS, ROS conversion, IoU-BEV NMS, remapper)
``e2e``                ``model(points)`` as served (its ``timing_ms`` medians are reported too)
``b2b``                back-to-back replays, one synchronise per round of ``--b2b-iters``: device time per forward
=====================  ================================================================================================

AICLK / power / temperature are sampled from sysfs during the run (``ttaw.profiling.AiclkSampler``), and the host
load average is recorded (the host stages move with it). ``--check`` (default) compares the served output of each
input with a stored fp32 CPU-reference ``/predict`` body (``--reference PATH`` per input, ``-`` for none; default:
``<stem>.<variant>.reference.json`` next to the input) with the container-smoke gates (``server/smoke_test.py``
``REFERENCE_GATES``). Always quote the configuration line (dispatch / CQs / grid) with the numbers.
"""
from __future__ import annotations

import argparse
import json
import os
import platform
import statistics
import time
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional

import numpy as np

from tt_centerpoint import CenterPoint
from tt_centerpoint.ttaw.profiling import AiclkSampler, StageBench, time_b2b

CODE = Path(__file__).resolve().parents[1]
SAMPLE = CODE / "tt_centerpoint" / "samples" / "test_pcd.npz"
NPY_FIELDS = ("x", "y", "z", "time_lag")     # research/centerpoint/public_data/inputs/*.npy (npy_xyzt)


def input_fn(path: Path) -> Callable[[], Any]:
    """What a client hands to ``model(...)`` for ``path``: the path itself (the API decodes it), or for a research
    ``.npy`` (an unnamed (N, 4) array) a ``PointCloud`` with the npy_xyzt field names, read inside the call."""
    if path.suffix == ".npy":
        from tt_centerpoint.ttaw import io as tio

        return lambda: tio.PointCloud(np.load(path, allow_pickle=False), NPY_FIELDS)
    return lambda: str(path)


def check_output(model, src: Callable[[], Any], reference: Optional[Path]) -> Dict[str, Any]:
    """Served output vs the stored fp32 CPU-reference ``/predict`` body (the container-smoke comparison)."""
    from tt_centerpoint.server import smoke_test as st
    from tt_centerpoint.ttaw.server import smoke

    out = model(src()).to_dict()
    res: Dict[str, Any] = {"num_detections": out["num_detections"], "counts": out["meta"].get("counts"),
                           "num_pillars": out["meta"].get("num_pillars")}
    if reference is not None and reference.is_file():
        metrics, fails = smoke.compare_with_reference(out, smoke.load_json(reference), gates=st.REFERENCE_GATES)
        res["reference"] = {"file": str(reference), "metrics": metrics, "failures": fails}
    return res


def bench_input(model, src: Callable[[], Any], *, iters: int, warmup: int, b2b_iters: int, b2b_rounds: int,
                name: str) -> Dict[str, Any]:
    import ttnn

    from tt_centerpoint.ttaw import io as tio
    from tt_centerpoint.ttaw.tensors import to_numpy
    from tt_centerpoint.ttaw.voxelize import assign_pillars, canvas_gather_index, decorate_pillar_features

    tr = model.runner                       # ttaw.trace.TraceRunner, variant "default"
    dev, pre, cfg = model.device, model.pre, model.config
    params = model.validate_params({})
    bench = StageBench(name)
    for _ in range(warmup):
        model(src())
    var = model.staging.variant             # the trace this input runs (PFN_BUCKETS: its pillar capacity)
    out_dev = tr.outputs(var)               # the persistent trace output (device)
    host_out = ttnn.allocate_tensor_on_host(out_dev.spec, dev)
    feat_name = model.graph.input_name(model.staging.capacity)
    slots = {k: tr._slot(k, "input") for k in (feat_name, "canvas_index")}
    from tt_centerpoint.host import fast

    scratch = np.zeros((pre.spec.max_pillars, pre.spec.max_points_per_pillar, 16), np.int16)
    occ = np.full(pre.spec.max_pillars, pre.spec.max_points_per_pillar, np.int32)   # HOST_STAGING=sparse
    for _ in range(iters):
        t0 = time.perf_counter()
        prepared = model._prepare(points=src())
        t1 = time.perf_counter()
        inputs = model.staging.write(prepared)
        t2 = time.perf_counter()
        tr.upload(inputs)
        ttnn.synchronize_device(dev)
        t3 = time.perf_counter()
        tr.replay(var)
        ttnn.synchronize_device(dev)
        t4 = time.perf_counter()
        rb = getattr(model, "_readback", None) if model.knobs.HOST_DECODE == "rows" and \
            model.knobs.HOST_READBACK == "tiled" else None
        rows = rb.read(tr.outputs(var)) if rb else tr.read(var)    # as served (api._forward)
        t5 = time.perf_counter()
        if model.knobs.HOST_DECODE == "rows":
            from tt_centerpoint.host.postprocess import HeadRows

            raw = (HeadRows(None, model.graph.head.slices, *model.graph.head_grid, tiled=rows, n_cols=rb.n_cols)
                   if rb else HeadRows(rows, model.graph.head.slices, *model.graph.head_grid))
        else:
            raw = model.graph.unpack(rows)
        t6 = time.perf_counter()
        model._postprocess(raw, prepared, params)
        t7 = time.perf_counter()
        for stage, a, b in (("pre", t0, t1), ("host_in", t1, t2), ("h2d", t2, t3), ("trace", t3, t4),
                            ("d2h", t4, t5), ("unpack", t5, t6), ("post", t6, t7)):
            bench.add(stage, (b - a) * 1e3)
        # the split rows (outside the served path; same data)
        with bench.stage("pre.load"):
            cloud = tio.load_points(src())
        with bench.stage("pre.densify"):
            pts, _, _ = pre.densified_points(cloud)
        with bench.stage("pre.assign"):
            if model.knobs.HOST_VOXELIZER in ("numba", "numba2"):
                pillars = fast.assign_pillars(pts, pre.spec, shuffle_seed=pre.shuffle_seed,
                                              version=2 if model.knobs.HOST_VOXELIZER == "numba2" else 1)
            else:
                pillars = assign_pillars(pts, pre.spec, shuffle_seed=pre.shuffle_seed)
        with bench.stage("pre.decorate"):     # numba: straight into bf16 rows (served inside host_in)
            if model.knobs.HOST_DECORATE == "numba" and model.knobs.HOST_STAGING == "sparse":
                fast.decorate_into(pillars, pre.spec, scratch, occ=occ, used=pillars.num_pillars)
            elif model.knobs.HOST_DECORATE == "numba":
                fast.decorate_into(pillars, pre.spec, scratch)
            else:
                decorate_pillar_features(pillars, pre.spec, encoder_in_feature_size=cfg.encoder_in_feature_size)
        with bench.stage("pre.index"):
            canvas_gather_index(pillars.coords, pillars.num_pillars, pre.spec, sentinel=pre.spec.max_pillars)
        for k, slot in slots.items():
            with bench.stage(f"h2d.{'features' if k == feat_name else k}"):
                ttnn.copy_host_to_device_tensor(inputs[k], slot.buffers[0], cq_id=0)
                ttnn.synchronize_device(dev)
        with bench.stage("d2h.copy"):
            ttnn.copy_device_to_host_tensor(out_dev, host_out, blocking=True)
        with bench.stage("d2h.to_numpy"):
            to_numpy(host_out)
    timing: List[Dict[str, float]] = []
    for _ in range(iters):
        t0 = time.perf_counter()
        out = model(src())
        bench.add("e2e", (time.perf_counter() - t0) * 1e3)
        timing.append(dict(out.timing_ms))
    rounds = [time_b2b(lambda: tr.replay(var), lambda: ttnn.synchronize_device(dev), n=b2b_iters)
              for _ in range(b2b_rounds)]
    for r in rounds:
        bench.add("b2b", r)
    b2b = statistics.median(rounds)
    stats = prepared.stats()
    return {"stages_ms": bench.summary(), "table": bench.table(),
            "timing_ms_median": {k: statistics.median(t[k] for t in timing) for k in timing[0]},
            "b2b_rounds_ms": rounds, "b2b_iters": b2b_iters, "device_fps_b2b": 1e3 / b2b,
            "e2e_fps_sync": 1e3 / bench.summary()["e2e"]["p50"],
            "frame": {k: stats.get(k) for k in ("num_points", "num_points_in_range", "num_pillars",
                                                "num_pillars_total", "pillar_overflow")},
            "trace_variant": var,
            "bytes": {"features": int(np.prod(slots[feat_name].shape)) * 2,
                      "canvas_index": int(np.prod(slots["canvas_index"].shape)) * 4,
                      "output": int(np.prod(model.graph.head_grid)) * int(model.graph.head.padded_channels) * 4}}


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--input", action="append", default=None,
                    help="cloud .npz / .pcd / .npy (npy: research npy_xyzt layout); repeatable; default: the sample")
    ap.add_argument("--reference", action="append", default=None,
                    help="fp32 CPU-reference /predict body per --input ('-' for none; default <stem>.<variant>"
                         ".reference.json next to the input)")
    ap.add_argument("--iters", type=int, default=100)
    ap.add_argument("--warmup", type=int, default=10)
    ap.add_argument("--b2b-iters", type=int, default=50)
    ap.add_argument("--b2b-rounds", type=int, default=5)
    ap.add_argument("--variant", default=None, help="base | tiny (default: CENTERPOINT_VARIANT or base)")
    ap.add_argument("--dispatch", default=None, choices=["eth", "worker"], help="default: CENTERPOINT_DISPATCH or eth")
    ap.add_argument("--cqs", type=int, default=None, choices=[1, 2],
                    help="command queues (default: CENTERPOINT_NUM_CQS or 1)")
    ap.add_argument("--weights-dir", default=None, help="holds base/ and tiny/ (default: the pinned HF snapshot)")
    ap.add_argument("--allow-fallback", action="store_true", help="accept a WORKER fallback of an ETH open")
    ap.add_argument("--no-check", dest="check", action="store_false")
    ap.add_argument("--tag", default="", help="label of this configuration in the output")
    ap.add_argument("--json")
    a = ap.parse_args()
    inputs = [Path(p) for p in (a.input or [str(SAMPLE)])]
    refs = [None if r in (None, "-") else Path(r) for r in (a.reference or [])] + [None] * len(inputs)
    load0 = os.getloadavg()
    t0 = time.perf_counter()
    with CenterPoint.from_pretrained(variant=a.variant, dispatch=a.dispatch, num_command_queues=a.cqs,
                                     weights_dir=a.weights_dir) as model:
        load_s = time.perf_counter() - t0
        info = dict(model.device_info)
        want = a.dispatch or os.environ.get("CENTERPOINT_DISPATCH", "eth")
        if info.get("dispatch") != want and not a.allow_fallback:
            raise SystemExit(f"device opened with dispatch {info.get('dispatch')!r}, asked for {want!r}")
        tag = a.tag or f"{info.get('dispatch')}-{info.get('num_command_queues')}cq {info.get('grid')}"
        res: Dict[str, Any] = {"tag": tag, "config": info, "variant": model.variant,
                               "precision": model.graph.policy.describe(), "trace": model.runner.describe(),
                               "load_s": load_s, "warmup_ms": dict(model.warmup_ms), "iters": a.iters,
                               "host": {"cpus": os.cpu_count(), "machine": platform.processor() or platform.machine(),
                                        "loadavg_start": load0}, "inputs": {}}
        with AiclkSampler(interval_s=0.05) as clk:
            for k, (path, ref) in enumerate(zip(inputs, refs)):
                src = input_fn(path)
                if ref is None and a.reference is None:
                    cand = path.parent / f"{path.stem}.{model.variant}.reference.json"
                    ref = cand if cand.is_file() else None
                r = bench_input(model, src, iters=a.iters, warmup=a.warmup, b2b_iters=a.b2b_iters,
                                b2b_rounds=a.b2b_rounds, name=f"{path.name} | {tag} | {model.variant}")
                r["input"] = str(path)
                if a.check:
                    r["check"] = check_output(model, src, ref)
                res["inputs"][f"{k}:{path.name}"] = r
                print(r["table"], flush=True)
                print(f"b2b rounds ms: {[round(x, 3) for x in r['b2b_rounds_ms']]}  "
                      f"timing_ms medians: { {k2: round(v, 2) for k2, v in r['timing_ms_median'].items()} }  "
                      f"frame: {r['frame']}", flush=True)
                if a.check:
                    print("check:", json.dumps(r["check"], default=str), flush=True)
        res["aiclk"] = clk.summary()
        res["trace_after"] = model.runner.describe()
        g = model.graph.describe()
        res["graph"] = {k: g.get(k) for k in ("conv_l1", "conv_l1_fallbacks", "conv_rm", "conv_l1_abh", "conv_chain",
                                              "conv_unchained", "deblock_rm", "heads", "head_sum")}
        print("graph:", json.dumps(res["graph"]), flush=True)
        res["host"]["loadavg_end"] = os.getloadavg()
    print(json.dumps({"tag": tag, "variant": res["variant"], "config": info, "aiclk": res["aiclk"],
                      "load_s": round(load_s, 2), "program_cache_entries":
                      res["trace_after"].get("program_cache_entries"),
                      "loadavg": [load0, res["host"]["loadavg_end"]]}, default=str), flush=True)
    if a.json:
        Path(a.json).parent.mkdir(parents=True, exist_ok=True)
        Path(a.json).write_text(json.dumps(res, indent=1, default=str) + "\n")


if __name__ == "__main__":
    main()