centerpoint-p150 / code /scripts /profile_ops.py
changh95's picture
tt-model push centerpoint-p150 (container)
18c340c verified
Raw History Blame Contribute Delete
7.35 kB
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Device profile of centerpoint-p150: one eager forward and one traced replay of the whole graph between Tracy
signposts, for one serve profile (``--variant base | tiny``).
ROOT=/home/ubuntu/experiments/tt-models
$ROOT/bin/devrun -t 3600 -- python -m tracy -r -p -v --no-web-server \\
-o $ROOT/generated/profiler/centerpoint_baseline code/scripts/profile_ops.py --variant base
tt-perf-report <ops_perf_results_*.csv> --start-signpost trace --end-signpost trace_end --tracing-mode
python code/scripts/profile_summary.py <the same csv> profile_summary.json --md profile_summary.md
Sections (signposts): ``eager`` .. ``eager_end``, one eager forward after the warm-up (``TraceRunner.run_eager``:
the same graph and programs as the trace, nothing compiled), and ``trace`` .. ``trace_end``, ``--replays`` replays
of the captured ``default`` trace (the served device path; the uploaded inputs are the voxelized ``--input``). The
device profiler buffer is flushed (``ttnn.ReadDeviceProfiler``) before and after each section. Inside the eager
section every module of the graph opens a signpost (``m:pfn``, ``m:scatter``, ``m:backbone.block<i>``,
``m:neck.deblock<i>``, ``m:head.shared``, ``m:head.hidden``, ``m:head.out``) and every backbone conv a layer
signpost (``c:backbone.block<i>.conv<j>``; ``--no-layer-signposts`` turns them off), so the ops of the eager forward,
and through the identical op order those of the replay, can be attributed to modules (``profile_summary.py``). The
output folder must be absolute and outside the bundle (PLAN.md 5.1).
"""
from __future__ import annotations
import argparse
import json
import time
from pathlib import Path
from typing import Callable, List, Sequence
import numpy as np
from tt_centerpoint import CenterPoint
from tt_centerpoint.ttaw.profiling import read_device_profiler, signpost, signposted
SAMPLE = Path(__file__).resolve().parents[1] / "tt_centerpoint" / "samples" / "test_pcd.npz"
class _Signposted:
"""A callable stand-in for a module that emits its signposts, then calls the module (attributes forward)."""
def __init__(self, inner, labels: Sequence[str]):
self.inner, self._labels = inner, list(labels)
def __call__(self, *args, **kwargs):
for label in self._labels:
signpost(label)
return self.inner(*args, **kwargs)
def __getattr__(self, name):
return getattr(self.inner, name)
def module_signposts(graph, layers: bool = True) -> Callable[[], None]:
"""Wrap the modules of a ``tt.model.TtCenterPoint`` (and the C19 scatter its forward calls) with signposting
stand-ins; returns the function that restores them."""
from tt_centerpoint.tt import model as tt_model
undo: List[Callable[[], None]] = []
def swap(obj, attr, labels):
inner = getattr(obj, attr)
setattr(obj, attr, _Signposted(inner, labels))
undo.append(lambda: setattr(obj, attr, inner))
def swap_item(seq, i, labels):
inner = seq[i]
seq[i] = _Signposted(inner, labels)
undo.append(lambda: seq.__setitem__(i, inner))
swap(graph, "pfn", ["m:pfn"])
pfns = getattr(graph, "pfns", None) # PFN_BUCKETS: _canvas runs graph.pfns[capacity]
if pfns is not None:
for cap in list(pfns):
swap_item(pfns, cap, ["m:pfn"])
scatter = tt_model.scatter_rows
def scatter_rows(*args, **kwargs):
signpost("m:scatter")
return scatter(*args, **kwargs)
tt_model.scatter_rows = scatter_rows
undo.append(lambda: setattr(tt_model, "scatter_rows", scatter))
gather = tt_model.gather_rows # PFN_PACK=k7: the PFN writes the table, the scatter gathers
def gather_rows(*args, **kwargs):
signpost("m:scatter")
return gather(*args, **kwargs)
tt_model.gather_rows = gather_rows
undo.append(lambda: setattr(tt_model, "gather_rows", gather))
for i, block in enumerate(graph.backbone.blocks):
for j in range(len(block)):
labels = ([f"m:backbone.block{i}"] if j == 0 else []) + ([f"c:backbone.block{i}.conv{j}"] if layers else [])
swap_item(block, j, labels)
for i in range(len(graph.neck.deblocks)):
swap_item(graph.neck.deblocks, i, [f"m:neck.deblock{i}"])
for name in ("shared", "hidden", "out"):
swap(graph.head, name, [f"m:head.{name}"])
if getattr(graph, "head_sum", "stock") == "k6": # K6: the partial convs run outside head.shared
swap(graph, "_shared_parts", ["m:head.shared"])
swap(graph, "_shared_part", ["m:head.shared"]) # NECK_L1: each part conv right after its deblock
def restore() -> None:
for fn in reversed(undo):
fn()
return restore
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--input", default=str(SAMPLE))
ap.add_argument("--variant", default=None, help="base | tiny (default: CENTERPOINT_VARIANT or base)")
ap.add_argument("--dispatch", default=None, choices=["eth", "worker"])
ap.add_argument("--cqs", type=int, default=None, choices=[1, 2])
ap.add_argument("--replays", type=int, default=1, help="replays inside the trace section")
ap.add_argument("--weights-dir", default=None)
ap.add_argument("--no-eager", dest="eager", action="store_false")
ap.add_argument("--no-layer-signposts", dest="layers", action="store_false")
a = ap.parse_args()
import ttnn
src = a.input
if src.endswith(".npy"):
from tt_centerpoint.ttaw import io as tio
src = tio.PointCloud(np.load(src, allow_pickle=False), ("x", "y", "z", "time_lag"))
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:
tr, dev = model.runner, model.device
print("loaded in %.1f s:" % (time.perf_counter() - t0), json.dumps(model.device_info), flush=True)
prepared = model._prepare(points=src)
out = model(src) # one served frame: upload + replay + readback
print(f"variant {model.variant}: {out.to_dict()['num_detections']} detections, "
f"{prepared.num_pillars} pillars", flush=True)
ttnn.synchronize_device(dev)
read_device_profiler(dev) # warm-up / capture / first frame out of the buffer
inputs = model.staging.write(prepared)
if a.eager:
restore = module_signposts(model.graph, layers=a.layers)
try:
with signposted("eager"):
tr.run_eager(model.staging.variant, inputs=inputs)
ttnn.synchronize_device(dev)
finally:
restore()
read_device_profiler(dev)
tr.upload(inputs)
ttnn.synchronize_device(dev)
read_device_profiler(dev)
with signposted("trace"):
tr.replay(model.staging.variant, n=a.replays)
ttnn.synchronize_device(dev)
read_device_profiler(dev)
print("trace:", json.dumps(tr.describe()), "replayed", model.staging.variant, flush=True)
if __name__ == "__main__":
main()