File size: 10,846 Bytes
23d1b53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2223bb
 
23d1b53
 
 
 
e2223bb
23d1b53
 
 
 
 
e2223bb
23d1b53
 
 
 
 
 
e2223bb
 
 
23d1b53
 
 
 
 
 
 
 
 
 
 
 
 
e2223bb
23d1b53
e2223bb
 
23d1b53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2223bb
23d1b53
 
 
 
e2223bb
23d1b53
e2223bb
 
 
 
 
 
 
 
 
 
 
 
 
23d1b53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2223bb
23d1b53
 
 
 
 
 
 
 
 
 
 
 
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
# 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()