xvla-base-p150 / code /scripts /bench_p150.py
changh95's picture
tt-model push xvla-base-p150 (container)
3aa087b verified
Raw History Blame Contribute Delete
10.1 kB
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Tenstorrent USA, Inc.
# SPDX-License-Identifier: Apache-2.0
"""In-process timing of the served X-VLA model on one Blackhole p150 (opens the device).
Boots exactly what the server boots -- it enters ``tt.server.app``'s lifespan with the
serve environment: weights at the pinned revision, device open, on-chip modules, warm-up
chunk and the trace-capture check -- then times, per ``--steps`` setting:
* device: back-to-back replays of the two captured metal traces (the 24-block action
transformer, run once per denoising step, and the 12-layer BART language encoder),
non-blocking, one synchronize per round;
* ``policy.predict_action_chunk(batch)`` on a preprocessed batch (3 views of 224x224,
32 language tokens), and its split into vision encoder / language encoder / action
transformer / the rest (forward hooks, separate iterations);
* the request handler ``predict()`` called in-process (base64 decode, preprocessing,
inference, the JSON-ready result; no HTTP).
python -u scripts/bench_p150.py --image media/pusht_synthetic.png --steps 1,10 --out /out/bench_p150.json
"""
from __future__ import annotations
import argparse
import asyncio
import base64
import json
import os
import platform
import statistics
import sys
import time
from pathlib import Path
CODE = Path(__file__).resolve().parents[1]
if str(CODE) not in sys.path:
sys.path.insert(0, str(CODE))
def _pct(xs, q):
s = sorted(xs)
k = (len(s) - 1) * q
lo, hi = int(k), min(int(k) + 1, len(s) - 1)
return s[lo] + (s[hi] - s[lo]) * (k - lo)
def summary(xs) -> dict:
return dict(n=len(xs), p50=_pct(xs, 0.5), p90=_pct(xs, 0.9), p99=_pct(xs, 0.99), mean=statistics.fmean(xs),
min=min(xs), max=max(xs))
def _cpu_model() -> str:
try:
for line in Path("/proc/cpuinfo").read_text().splitlines():
if line.startswith("model name"):
return line.split(":", 1)[1].strip()
except OSError:
pass
return platform.processor()
def _device_facts(ttnn, dev) -> dict:
g = dev.compute_with_storage_grid_size()
facts = dict(compute_grid=f"{g.x}x{g.y}", arch=str(dev.arch()) if hasattr(dev, "arch") else None)
for name in ("num_hw_cqs", "num_program_cache_entries"):
fn = getattr(dev, name, None)
if callable(fn):
try:
facts[name] = int(fn())
except Exception: # noqa: BLE001
pass
# dispatch core type: the API differs between tt-metal versions, so probe
for owner, label in ((dev, "device"), (ttnn, "ttnn"), (getattr(ttnn, "device", None), "ttnn.device")):
if owner is None:
continue
for name in dir(owner):
if "dispatch_core" in name.lower() and callable(getattr(owner, name, None)):
try:
facts[f"{label}.{name}"] = str(getattr(owner, name)())
except Exception: # noqa: BLE001
pass
return facts
def time_replays(ttnn, dev, trace_id, rounds: int, per_round: int) -> list[float]:
ms = []
for _ in range(rounds):
ttnn.synchronize_device(dev)
t0 = time.perf_counter()
for _ in range(per_round):
ttnn.execute_trace(dev, trace_id, blocking=False)
ttnn.synchronize_device(dev)
ms.append((time.perf_counter() - t0) * 1e3 / per_round)
return ms
def run(a, app, ttnn, torch) -> dict:
st = app.STATE
policy, dev = st["policy"], st["device"]
img = base64.b64encode(a.image.read_bytes()).decode("ascii")
state = [0.0] * st["state_dim_default"]
batch, _ = app._build_batch([img] * 3, a.instruction, state, 0)
res = dict(device=_device_facts(ttnn, dev), fused=st.get("fused"), per_steps={})
print(f"device: {res['device']}", flush=True)
model = policy.model
stack_tg = model.transformer.blocks.trace
bart_tg = model.vlm.language_model.model.encoder.trace
for tg in (stack_tg, bart_tg):
if tg.trace_id is None:
raise SystemExit(f"trace {tg.name} was not captured: {tg.status()}")
rep = dict(
action_transformer_per_step=summary(time_replays(ttnn, dev, stack_tg.trace_id, a.rounds, a.per_round)),
language_encoder=summary(time_replays(ttnn, dev, bart_tg.trace_id, a.rounds, a.per_round)),
rounds=a.rounds, replays_per_round=a.per_round,
)
res["trace_replay_ms"] = rep
print(f"trace replay: stack {rep['action_transformer_per_step']['p50']:.3f} ms/step, "
f"BART {rep['language_encoder']['p50']:.3f} ms", flush=True)
for steps in [int(x) for x in a.steps.split(",") if x.strip()]:
n = a.n
policy.config.num_denoising_steps = steps
row = {}
# 1. policy.predict_action_chunk on the preprocessed batch
for _ in range(3):
torch.manual_seed(a.seed)
policy.predict_action_chunk(batch)
ms = []
for _ in range(n):
torch.manual_seed(a.seed)
t0 = time.perf_counter()
policy.predict_action_chunk(batch)
ms.append((time.perf_counter() - t0) * 1e3)
row["predict_action_chunk_ms"] = summary(ms)
# 2. split by stage (separate iterations: the hooks add a little overhead)
stages = {"vision_encoder": [], "language_encoder": [], "action_transformer": []}
marks = {}
def pre(name):
return lambda *_: marks.__setitem__(name, time.perf_counter())
def post(name):
return lambda *_: stages[name].append((time.perf_counter() - marks[name]) * 1e3)
vlm = model.vlm
enc_orig = vlm._encode_image
def enc_timed(*args, **kw):
t0 = time.perf_counter()
out = enc_orig(*args, **kw)
stages["vision_encoder"].append((time.perf_counter() - t0) * 1e3)
return out
vlm._encode_image = enc_timed
hooks = [
vlm.language_model.model.encoder.register_forward_pre_hook(pre("language_encoder")),
vlm.language_model.model.encoder.register_forward_hook(post("language_encoder")),
model.transformer.register_forward_pre_hook(pre("action_transformer")),
model.transformer.register_forward_hook(post("action_transformer")),
]
tot = []
nb = max(n // 2, 2)
try:
for _ in range(nb):
torch.manual_seed(a.seed)
t0 = time.perf_counter()
policy.predict_action_chunk(batch)
tot.append((time.perf_counter() - t0) * 1e3)
finally:
for h in hooks:
h.remove()
del vlm._encode_image # back to the class method
per_call = {k: sum(v) / nb for k, v in stages.items()}
per_call["action_transformer_per_step"] = per_call["action_transformer"] / steps
per_call["rest"] = statistics.fmean(tot) - sum(per_call[k] for k in stages)
per_call["total_mean"] = statistics.fmean(tot)
per_call["iterations"] = nb
row["stage_mean_ms"] = per_call
# 3. the request handler, in-process
req = app.PredictRequest(images=[img] * 3, instruction=a.instruction, state=state, seed=a.seed,
num_denoising_steps=steps)
for _ in range(3):
app.predict(req)
ms, srv = [], []
first = None
for _ in range(n):
t0 = time.perf_counter()
out = app.predict(req)
ms.append((time.perf_counter() - t0) * 1e3)
srv.append(out["timing_ms"]["total"])
first = first or out["actions"]
row["handler_ms"] = summary(ms)
row["handler_timing_total_ms"] = summary(srv)
row["actions_first_row"] = first[0][:10]
res["per_steps"][str(steps)] = row
print(f"steps {steps:>2}: predict_action_chunk p50 {row['predict_action_chunk_ms']['p50']:.2f} "
f"p99 {row['predict_action_chunk_ms']['p99']:.2f} ms (n {n}) | handler p50 {row['handler_ms']['p50']:.2f} ms | "
f"stages {json.dumps({k: round(v, 2) for k, v in per_call.items()})}", flush=True)
policy.config.num_denoising_steps = st["default_steps"]
return res
async def amain(a) -> dict:
import torch
import tt.server.app as app
t0 = time.perf_counter()
load0 = os.getloadavg()
async with app.lifespan(app.app):
boot_s = time.perf_counter() - t0
import ttnn
res = run(a, app, ttnn, torch)
res.update(
boot_seconds=boot_s, image=a.image.name, image_bytes=a.image.stat().st_size, views=3,
instruction=a.instruction, seed=a.seed,
env={k: v for k, v in sorted(os.environ.items())
if k.startswith(("TT_", "XVLA_", "HF_MODEL", "MESH_", "TT_MESH"))},
host=dict(cpu=_cpu_model(), cpus=os.cpu_count(), loadavg_start=load0, loadavg_end=os.getloadavg()),
versions=dict(python=platform.python_version(), torch=torch.__version__,
ttnn=getattr(sys.modules.get("ttnn"), "__version__", None)),
utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
)
return res
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--image", type=Path, required=True, help="PNG/JPEG used for all 3 views")
ap.add_argument("--instruction", default="push the T")
ap.add_argument("--steps", default="1,10")
ap.add_argument("--n", type=int, default=20, help="timed calls per steps setting (half of it for the stage split)")
ap.add_argument("--rounds", type=int, default=20)
ap.add_argument("--per-round", type=int, default=50)
ap.add_argument("--seed", type=int, default=42)
ap.add_argument("--out", type=Path, default=None)
a = ap.parse_args()
res = asyncio.run(amain(a))
if a.out:
a.out.write_text(json.dumps(res, indent=1, default=str))
print(f"wrote {a.out}")
return 0
if __name__ == "__main__":
raise SystemExit(main())