changh95's picture
tt-model push vla-jepa-base-p150 (container)
e2223bb verified
Raw History Blame Contribute Delete
10.8 kB
# SPDX-License-Identifier: Apache-2.0
"""Latency of VLA-JEPA on one p150 (run through bin/devrun; in the container image: python code/scripts/bench.py).
ROOT=/home/ubuntu/experiments/tt-models
$ROOT/bin/devrun -t 2400 -- $ROOT/tt-metal/python_env/bin/python -u \
$ROOT/bundles/vla-jepa-base-p150/code/scripts/bench.py --ckpt pretrain --reps 60 \
--out $ROOT/logs/vla-jepa/bench_pretrain_eth.json
The served model (all four buckets, every full-call trace captured at init: ``load_s`` / ``warmup_s`` / ``init_s``).
Per bucket (224 = "open the drawer", 256 = the long golden prompt, 288 / 320 = the official long-prompt golden
``b288_mid`` / ``b320_mid``): the full-call trace (VISION + PREFIX + EXPERT, 4 Euler steps, ONE trace) replayed
``--reps`` times (median / p10 / p90, host waits for the end of every replay), the
three stage traces replayed one at a time (VISION, PREFIX, EXPERT total) and an ``expert_prep`` trace (cross K/V +
state token) so that per step = (EXPERT - prep) / 4; host pre (tokenise, image preprocess, rope, mask, embedding
gather), upload (host tilize + copy into the fixed buffers) and readback + post-processing of a full ``__call__``.
Without the workspace golden dumps (e.g. in the container image) the shipped sample is run in every bucket
(``--sample``, forced with ``prompt_bucket``), without the PCC column. ``--weights-dir``: a local snapshot of the
checkpoint (default: ``VLAJEPA.resolve_weights``, i.e. ``$VLA_JEPA_WEIGHTS_DIR`` or the Hub / HF cache at the pinned
commit); the tokenizer is the packaged one (``--tokenizer-dir`` overrides).
"""
import argparse
import json
import os
import statistics
import sys
import time
CODE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, CODE)
import torch # noqa: E402
from tt_vla_jepa.reference.golden import GoldenSet, LongGoldenSet, pcc # noqa: E402
def stats(ts):
ts = sorted(ts)
n = len(ts)
return {"median": statistics.median(ts), "p10": ts[int(0.1 * (n - 1))], "p90": ts[int(0.9 * (n - 1))],
"min": ts[0], "mean": sum(ts) / n, "n": n}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", default="pretrain")
ap.add_argument("--dispatch", default="eth")
ap.add_argument("--reps", type=int, default=60)
ap.add_argument("--cases", default="2,0") # golden case indices (bucket 224, bucket 256)
ap.add_argument("--long", default="b288_mid,b320_mid") # long-golden case names (buckets 288, 320)
ap.add_argument("--no-stages", action="store_true")
ap.add_argument("--engine", default=None, help="tt.model.resolve_engine syntax, e.g. expert=ttnn")
ap.add_argument("--out", default="")
ap.add_argument("--sample", action="store_true", help="the shipped sample in every bucket (no goldens needed)")
ap.add_argument("--weights-dir", default=None)
ap.add_argument("--tokenizer-dir", default=None)
ap.add_argument("--num-cameras", type=int, default=None, help="configuration (round 4 / Config): 1..4, default 2")
ap.add_argument("--num-steps", type=int, default=None, help="configuration: flow-matching steps 1..16, default 4")
args = ap.parse_args()
torch.set_num_threads(4)
from tt_vla_jepa.device import close_device, describe_device, open_device
from tt_vla_jepa.tt.model import VLAJEPATT
from tt_vla_jepa.ttaw.profiling import AiclkSampler
from tt_vla_jepa.api import VLAJEPA, resolve_tokenizer_dir
from tt_vla_jepa.reference.config import CHECKPOINTS, DEFAULT_DIRS
golden_ok = os.path.isfile(os.path.join(DEFAULT_DIRS["golden"], f"{args.ckpt}_fp32", "manifest.json"))
use_sample = args.sample or not golden_ok or (args.num_cameras or 2) != 2
wdir = args.weights_dir or str(VLAJEPA.resolve_weights(CHECKPOINTS[args.ckpt].repo)) # before the device opens
dev = open_device(dispatch=args.dispatch)
res = {"device": describe_device(dev), "ckpt": args.ckpt, "reps": args.reps, "presets": [], "weights_dir": wdir}
try:
t0 = time.perf_counter()
m = VLAJEPATT(dev, args.ckpt, engine=args.engine, ckpt_dir=wdir,
qwen_dir=str(resolve_tokenizer_dir(args.tokenizer_dir)), num_cameras=args.num_cameras,
num_steps=args.num_steps) # served configuration: all buckets
res["configuration"] = {"num_cameras": m.num_cameras, "num_steps": m.num_steps, "vision_runs": m.vision_runs}
res["engine"] = dict(m.engine)
res["init_s"] = time.perf_counter() - t0
res["precision"] = m.prec.as_dict()
res["load_s"] = m.load_seconds
res["warmup_s"] = m.warmup_seconds
res["buckets"] = list(m.buckets)
presets = []
if use_sample:
from tt_vla_jepa import io as tio
from tt_vla_jepa.api import load_sample
s = load_sample()
views = [tio.load_image(p) for p in s["images"]]
views = [views[i % 2] for i in range(m.num_cameras)] # the sample's 2 cameras repeated / truncated
state = [0.0] * CHECKPOINTS[args.ckpt].state_dim if CHECKPOINTS[args.ckpt].has_state_input else None
for b in m.buckets: # the sample's task needs 225 rows (2 cameras): bucket 224 gets a shorter instruction
ins = s["instruction"] if m.fmt.s_trim(s["instruction"]) <= b else "pick up the black bowl"
presets.append((f"sample_b{b}", views, ins, state, VLAJEPA.make_noise(0)[0], None, b))
gs = GoldenSet(args.ckpt, "fp32") if not use_sample else None
for ci in ([int(x) for x in args.cases.split(",") if x] if not use_sample else []):
g = gs.case(ci)
gv, gp, r = g["vision"], g["prefix"], g["run"]
presets.append((ci, list(gv["views_uint8"]), gp["prompt"], r["state_raw"], r["noise"][0],
r["actions_norm"][0], None))
if args.long and not use_sample:
lg = LongGoldenSet()
for name in args.long.split(","):
g = lg.get(args.ckpt, name)
presets.append((name, list(g["views"]), g["prompt"], g["state_raw"], g["noise"][0],
g["actions_norm"][0], None))
for ci, views, prompt, state, noise, gold, force in presets:
req = m.fmt(views, prompt, state, noise, force)
b = req.bucket
row = {"case": ci, "bucket": b, "n_pad": req.prefix.n_pad, "prompt": prompt}
a = m.run_traced(req)
if gold is not None:
row["pcc_vs_golden"] = pcc(a, gold)
for _ in range(3):
m.replay(b, "full")
ts = []
clk = AiclkSampler(interval_s=0.05).start() # the chip clock: sustained back-to-back replays throttle it
for _ in range(args.reps):
t1 = time.perf_counter()
m.replay(b, "full")
ts.append((time.perf_counter() - t1) * 1e3)
clk.stop()
row["full_replay_ms"] = stats(ts)
row["full_replay_clock"] = clk.summary()
# the same with a 10 ms host gap before each replay (a served request's duty cycle: the chip keeps its
# clock; OPT_REPORT.md round 4)
ts = []
clk = AiclkSampler(interval_s=0.05).start()
for _ in range(args.reps):
time.sleep(0.01)
t1 = time.perf_counter()
m.replay(b, "full")
ts.append((time.perf_counter() - t1) * 1e3)
clk.stop()
row["full_replay_gap10_ms"] = stats(ts)
row["full_replay_gap10_clock"] = clk.summary()
if (b, "split") in m.traces: # the serve mode's two traces (VISION | PREFIX + EXPERT) back to back
for _ in range(3):
m.replay(b, "split")
ts = []
for _ in range(args.reps):
t1 = time.perf_counter()
m.replay(b, "split")
ts.append((time.perf_counter() - t1) * 1e3)
row["split_replay_ms"] = stats(ts)
# a new instruction every call (the per-instruction cache emptied first): tokenisation, embedding gather,
# rope / mask tables and their upload are on the request path (built while the VISION runs)
cold = []
for _ in range(max(10, args.reps // 3)):
m.fmt._text_cache.clear()
m._resident.clear()
t1 = time.perf_counter()
m(views, prompt, state, noise, force)
cold.append((time.perf_counter() - t1) * 1e3)
row["call_new_instruction_ms"] = stats(cold)
# full __call__ split (host pre / upload / replay / readback+post)
parts = {"host_pre_ms": [], "upload_ms": [], "device_ms": [], "readback_post_ms": [], "e2e_ms": []}
for _ in range(max(10, args.reps // 3)):
t1 = time.perf_counter()
m(views, prompt, state, noise, force)
e2e = (time.perf_counter() - t1) * 1e3
lt = m.last_times
for k in ("host_pre_ms", "upload_ms", "device_ms", "readback_post_ms"):
parts[k].append(getattr(lt, k))
parts["e2e_ms"].append(e2e)
row["call"] = {k: stats(v) for k, v in parts.items()}
if args.no_stages:
print(json.dumps(row), flush=True)
res["presets"].append(row)
continue
# stage traces (timing only; released right after)
t0 = time.perf_counter()
mode = "stages+prep" if m.engine["expert"] == "ttnn" else "stages" # the megakernel has no prep stage
m.capture(b, mode, warm_req=req)
row["capture_stages_s"] = time.perf_counter() - t0
m.replay(b, mode)
names = ["vision", "prefix", "expert"] + (["expert_prep"] if mode == "stages+prep" else [])
st = {n: [] for n in names}
for _ in range(args.reps):
for i, n in enumerate(names):
t1 = time.perf_counter()
m.replay(b, mode, only=i)
st[n].append((time.perf_counter() - t1) * 1e3)
row["stage_replay_ms"] = {n: stats(v) for n, v in st.items()}
if mode == "stages+prep":
ex, pr = row["stage_replay_ms"]["expert"]["median"], row["stage_replay_ms"]["expert_prep"]["median"]
row["per_step_ms"] = (ex - pr) / m.num_steps
m.release(b, mode)
print(json.dumps(row), flush=True)
res["presets"].append(row)
finally:
close_device(dev)
if args.out:
with open(args.out, "w") as f:
json.dump(res, f, indent=1)
if __name__ == "__main__":
main()